Should I use int or Int32

2018-12-31 15:43发布

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 given. Is there a reason, and should I care?

30条回答
有味是清欢
2楼-- · 2018-12-31 16:21

int is the same as System.Int32 and when compiled it will turn into the same thing in CIL.

We use int by convention in C# since C# wants to look like C and C++ (and Java) and that is what we use there...

BTW, I do end up using System.Int32 when declaring imports of various Windows API functions. I am not sure if this is a defined convention or not, but it reminds me that I am going to an external DLL...

查看更多
唯独是你
3楼-- · 2018-12-31 16:21

int and Int32 is the same. int is an alias for Int32.

查看更多
倾城一夜雪
4楼-- · 2018-12-31 16:23

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.
查看更多
人间绝色
5楼-- · 2018-12-31 16:23

You should not care. If size is a concern I would use byte, short, int, then long. The only reason you would use an int larger than int32 is if you need a number higher than 2147483647 or lower than -2147483648.

Other than that I wouldn't care, there are plenty of other items to be concerned with.

查看更多
情到深处是孤独
6楼-- · 2018-12-31 16:23

According to the Immediate Window in Visual Studio 2012 Int32 is int, Int64 is long. Here is the output:

sizeof(int)
4
sizeof(Int32)
4
sizeof(Int64)
8
Int32
int
    base {System.ValueType}: System.ValueType
    MaxValue: 2147483647
    MinValue: -2147483648
Int64
long
    base {System.ValueType}: System.ValueType
    MaxValue: 9223372036854775807
    MinValue: -9223372036854775808
int
int
    base {System.ValueType}: System.ValueType
    MaxValue: 2147483647
    MinValue: -2147483648
查看更多
步步皆殇っ
7楼-- · 2018-12-31 16:24

I always use the system types - e.g., Int32 instead of int. I adopted this practice after reading Applied .NET Framework Programming - author Jeffrey Richter makes a good case for using the full type names. Here are the two points that stuck with me:

  1. Type names can vary between .NET languages. For example, in C#, long maps to System.Int64 while in C++ with managed extensions, long maps to Int32. Since languages can be mixed-and-matched while using .NET, you can be sure that using the explicit class name will always be clearer, no matter the reader's preferred language.

  2. Many framework methods have type names as part of their method names:

    BinaryReader br = new BinaryReader( /* ... */ );

    float val = br.ReadSingle(); // OK, but it looks a little odd...

    Single val = br.ReadSingle(); // OK, and is easier to read

查看更多
登录 后发表回答