Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use uint in C# for values that can't be negative?

Tags:

c#

integer

I have just tried implementing a class where numerous length/count properties, etc. are uint instead of int. However, while doing so I noticed that it's actually painful to do so, like as if no one actually wants to do that.

Nearly everything that hands out an integral type returns an int, therefore requiring casts in several points. I wanted to construct a StringBuffer with its buffer length defaulted to one of the fields in that class. Requires a cast too.

So I wondered whether I should just revert to int here. I'm certainly not using the entire range anyway. I just thought since what I'm dealing with there simply can't be negative (if it was, it'd be an error) it'd be a nice idea to actually use uint.

P.S.: I saw this question and this at least explains why the framework itself always uses int but even in own code it's actually cumbersome to stick to uint which makes me think it apparently isn't really wanted.

like image 216
Joey Avatar asked Jan 06 '10 13:01

Joey


People also ask

Does C have Uint?

The C language defines several integer data types: integer, short integer, long integer, and character, all in both signed and unsigned varieties. The GNU C compiler extends the language to contain long long integers as well.

What is Uint in C programming?

uint is a keyword that is used to declare a variable which can store an integral type of value (unsigned integer) from the range of 0 to 4,294,967,295. It keyword is an alias of System.

Is unsigned int same as Uint?

uint isn't a standard type - unsigned int is. and what does this fact implies? That code written with uint won't be inherently portable unless uint is a typedef that you declare actually inside that code.

Is Uint smaller than int?

int is shorter to type than uint .


2 Answers

I'll add to the other answers also that using uint as type of a public field, property, method, parameter, and so on, is a violation of the Common Language Specification rules and to be avoided when possible.

like image 64
Eric Lippert Avatar answered Oct 23 '22 18:10

Eric Lippert


While strictly you should use uint for variables that hold non-negative integer you have come across one of reasons why it's not always practicable.

In this case I don't think the reduction in readability that comes with having to do casts is worth it.

like image 41
ChrisF Avatar answered Oct 23 '22 18:10

ChrisF