Should I use int or Int32

前端 未结 30 2125
野性不改
野性不改 2020-11-22 11:52

In C#, int and Int32 are the same thing, but I\'ve read a number of times that int is preferred over Int32 with no reason

相关标签:
30条回答
  • 2020-11-22 12:25

    I always use the aliased types (int, string, etc.) when defining a variable and use the real name when accessing a static method:

    int x, y;
    ...
    String.Format ("{0}x{1}", x, y);
    

    It just seems ugly to see something like int.TryParse(). There's no other reason I do this other than style.

    0 讨论(0)
  • 2020-11-22 12:26

    int is a C# keyword and is unambiguous.

    Most of the time it doesn't matter but two things that go against Int32:

    • You need to have a "using System;" statement. using "int" requires no using statement.
    • It is possible to define your own class called Int32 (which would be silly and confusing). int always means int.
    0 讨论(0)
  • 2020-11-22 12:26

    int is the C# language's shortcut for System.Int32

    Whilst this does mean that Microsoft could change this mapping, a post on FogCreek's discussions stated [source]

    "On the 64 bit issue -- Microsoft is indeed working on a 64-bit version of the .NET Framework but I'm pretty sure int will NOT map to 64 bit on that system.

    Reasons:

    1. The C# ECMA standard specifically says that int is 32 bit and long is 64 bit.

    2. Microsoft introduced additional properties & methods in Framework version 1.1 that return long values instead of int values, such as Array.GetLongLength in addition to Array.GetLength.

    So I think it's safe to say that all built-in C# types will keep their current mapping."

    0 讨论(0)
  • 2020-11-22 12:27

    They both declare 32 bit integers, and as other posters stated, which one you use is mostly a matter of syntactic style. However they don't always behave the same way. For instance, the C# compiler won't allow this:

    public enum MyEnum : Int32
    {
        member1 = 0
    }
    

    but it will allow this:

    public enum MyEnum : int
    {
        member1 = 0
    }
    

    Go figure.

    0 讨论(0)
  • 2020-11-22 12:27

    I know that the best practice is to use int, and all MSDN code uses int. However, there's not a reason beyond standardisation and consistency as far as I know.

    0 讨论(0)
  • 2020-11-22 12:27

    Once upon a time, the int datatype was pegged to the register size of the machine targeted by the compiler. So, for example, a compiler for a 16-bit system would use a 16-bit integer.

    However, we thankfully don't see much 16-bit any more, and when 64-bit started to get popular people were more concerned with making it compatible with older software and 32-bit had been around so long that for most compilers an int is just assumed to be 32 bits.

    0 讨论(0)
提交回复
热议问题