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?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
In my experience it's been a convention thing. I'm not aware of any technical reason to use int over Int32, but it's:
I'm especially fond of that last one. :)
I use int in the event that Microsoft changes the default implementation for an integer to some new fangled version (let's call it Int32b).
Microsoft can then change the int alias to Int32b, and I don't have to change any of my code to take advantage of their new (and hopefully improved) integer implementation.
The same goes for any of the type keywords.
Use of Int or Int32 are the same Int is just sugar to simplify the code for the reader.
Use the Nullable variant Int? or Int32? when you work with databases on fields containing null. That will save you from a lot of runtime issues.
You shouldn't care. You should use
int
most of the time. It will help the porting of your program to a wider architecture in the future (currentlyint
is an alias toSystem.Int32
but that could change). Only when the bit width of the variable matters (for instance: to control the layout in memory of astruct
) you should useint32
and others (with the associated "using System;
").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 useint
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 anint
if appropriate, but should take care changingInt32
s in the same way.The resulting code will be identical: the difference is purely one of readability or code appearance.
A while back I was working on a project with Microsoft when we had a visit from someone on the Microsoft .NET CLR product team. This person coded examples and when he defined his variables he used “Int32” vs. “int” and “String” vs. “string”.
I had remembered seeing this style in other example code from Microsoft. So, I did some research and found that everyone says that there is no difference between the “Int32” and “int” except for syntax coloring. In fact, I found a lot of material suggesting you use “Int32” to make your code more readable. So, I adopted the style.
The other day I did find a difference! The compiler doesn’t allow you to type enum using the “Int32”, but it does when you use “int”. Don’t ask me why because I don’t know yet.
Example:
This works.
Taken from: Int32 notation vs. int