Difference of using int and uint and when to use
Asked Answered
H

3

18

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.

Hydrargyrum answered 18/6, 2010 at 9:21 Comment(1)
Related: #34352Exocarp
E
18

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.

Elodea answered 18/6, 2010 at 9:24 Comment(6)
so better stick with only int in practical?Hydrargyrum
@Thickbook: Yes, until you have a very clear reason to use uint, which will be rare.Elodea
@ThickBook: Yes, I would also stick with int in practice. Even if you don't need negative numbers, there is hardly any support for uint on most of the interfaces. Casting is not so trivial, because uint could be too high. Just int is standard, for instance also for Count and Length properties, which are never negative by definition.Twelve
@Stefan: right. Count and Length are signed because it would be awkward if the result of IndexOf (where -1 == not found) was of a different type.Elodea
uint is used a lot in embedded technology. Communication with external instruments.Betoken
@enrico: That is what I meant with P/Invoke use.Elodea
G
5

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.

Gentlemanfarmer answered 18/6, 2010 at 9:25 Comment(0)
H
3

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.

Hypnogenesis answered 18/6, 2010 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.