Should I use int or Int32
The two are indeed synonymous; int
will be a little more familiar looking, Int32
makes the 32-bitness more explicit to those reading your code. I would be inclined to use int
where I just need 'an integer', Int32
where the size is important (cryptographic code, structures) so future maintainers will know it's safe to enlarge an int
if appropriate, but should take care changing Int32
s in the same way.
The resulting code will be identical: the difference is purely one of readability or code appearance.
ECMA-334:2006 C# Language Specification (p18):
Each of the predefined types is shorthand for a system-provided type. For example, the keyword
int
refers to the structSystem.Int32
. As a matter of style, use of the keyword is favoured over use of the complete system type name.
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.
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:
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.-
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
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.