What is the difference between using int and uint? All the examples I have seen so far are using int for integers. Any advantage of using uint? Thanks开发者_开发百科.
uint
means unsigned int, you can use it for a 0 .. +4G range
where the normal (signed) int has a -2G .. +2G range.
When to use it? Almost never. It is not a CLS compliant type so you should never use it in the public interface of an assembly. Not all .NET languages can handle it.
Their main use is in P/Invoke to unmanaged code and some rare bitmask situations. In .NET, we do most bitmasking with normal signed ints.
First of all, uint is not CLS-compliant (other languages, that target the .NET platform do not necessarily implement it), and you should avoid using it in a public api whenever possible. Well, and of course they differ by range (0...4,294,967,295) for uint and (-2,147,483,648 to 2,147,483,647) for int.
The main difference is quite simply that int is signed, while uint is unsigned. Because uint doesn't allow for negative numbers, it has a range of 0 to 4,294,967,295, compared to the range of -2,147,483,648 to 2,147,483,647 for an int
If you have a scenario where you cannot have negative integers or it doesn't make sense to have a negative value, then unsigned integers can be a good choice. However, if you don't need the extra range and simply never go below 0, then it doesn't really matter and you can save a character by using an int.
精彩评论