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

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.

-------------Problems Reply------------

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.

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.

A negative value is often used to signal an error condition, and the size of a operation is often returned by a function call; a negative value may therefore signal error without resorting to an exception mechanism.

Also note that .NET often builds upon straight C libraries, therefore it is sensible to continue this convention. If you require a larger index space you can break the convention for different error signalling mechanism.

My personal feeling is that you should probably just stick to int. It's not worth adding a cast to pretty much every single property access just to reclaim a numeric range that .NET's unlikely to let you use anyway.

Using an int is also helpful to detect integer overflow in operations.

IMO, the drawback of using uint is that it obscures error conditions. The equivalents of the following code aren't as nice:

if (len < 0)
terminate_program("length attained impossible value.");

Of course your programs should not miscalculate anything to begin with, but I feel they also should be written to rapidly detect numerical erros without propagation. In the case where a MaxValue of 2^31 is enough, I say use int along with proper use of System.Diagnostics.Debug.Assert() and corresponding error-checks as exemplified above.

If you do use uint use it along with checked to prevent underflow and get the same results. However I have found that check is a little bit difficult to apply to existing code that uses casts for some purpose.

Don't swim upstream if you don't have to. Not litering your code with casts makes your code more readable. Further, if your possible values fit within an int, then using an int is not a problem.

If you're afraid you might overflow an int, then there by all means.. but don't prematurely optimize.

I would say the improved readability of minimizing casts outweighs the slightly elevated risk of a bug with using int.

If you want to check that a value is positive, a better way is probably just by using assert (note this is just a debugging technique - you should ensure that this never occurs in the final code).

using System.Diagnostics;
Debug.Assert (i > 0);

Category:c# Views:0 Time:2010-01-06
Tags: c# integer

Related post

  • In C# should I use uint or int for values that are never supposed to be negative? 2010-06-03

    Possible Duplicate: Should I use uint in C# for values that can’t be negative? Suppose that the MaxValue of (roughly :) ) 2^31 vs 2^32 does not matter. On one hand, using uint seems nice because it is self-explanatory, it indicates (and promises?) th

  • Should I use uint if my function is logically intended to return only natural numbers? 2011-06-03

    Let's consider a function which gets a person's birth date and returns his age (in whole years). In case of the date is in future it throws an exception. What type should it return - uint or int? uint seems logical as a natural constraint. Or is it b

  • how many distinct numbers are from 1.5 x 10^(-45) to 3.4 x 10^38? 2009-07-19

    How many distinct numbers are from 1.5 x 10-45 to 3.4 x 1038 (IEE754 single precision floats)? --------------Solutions------------- Assuming that you are talking about the range in IEEE single-precision float (the 1.5 x 10^-45 is the smallest positiv

  • .NET primitives and type hierarchies, why was it designed like this? 2009-11-05

    I would like to understand why on .NET there are nine integer types: Char, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, and UInt64; plus other numeric types: Single, Double, Decimal; and all these types have no relation at all. When I first star

  • C# - What could cause overflow checking here? 2010-02-24

    I am accustomed to C# not performing overflow checks, as the language spec states (§7.5.12): For non-constant expressions (expressions that are evaluated at run-time) that are not enclosed by any checked or unchecked operators or statements, the defa

  • What type to use in code and database for huge file size? 2010-11-04

    My project (C#) deals with many files about 1 MB ~ 2 GB in size. SQL server 2008 database is used. In long-term I need to do some operations over them like total sum of their size and ... At first glance I was planned to store their size in byte (in

  • Why is Array.Length an int, and not an uint 2008-08-08

    This question already has an answer here: Why does .NET use int instead of uint in certain classes? 7 answers Why is Array.Length an int, and not an uint. This bothers me (just a bit), because a length value can never by negative. This also forced me

  • How to parse hex values into a uint? 2008-09-19

    uint color; bool parsedhex = uint.TryParse(TextBox1.Text, out color); //where Text is of the form 0xFF0000 if(parsedhex) //... doesn't work. What am i doing wrong? --------------Solutions------------- Try Convert.ToUInt32(hex, 16) //Using ToUInt32 no

  • Converting string to uint in actionscript / Flex 2008-09-25

    I am creating a component and want to expose a color property as many flex controls do, lets say I have simple component like this, lets call it foo_label: <mx:Canvas> <mx:Script> [Bindable] public var color:uint; </mx:Script> <m

  • Difference of two 'uint' 2008-10-26

    When you attempt to declare an unsigned variable in C#.NET with a value outside its value range it is flagged as a compiler error, but if you produce a negative value at runtime and assign it to that variable at runtime the value wraps. uint z = -1;

  • What is the reason for specifying an Enum as uint? 2009-01-05

    I came across some Enumerators that inherited uint. I couldn't figure out why anyone would do this. Example: Enum myEnum : uint { ... } Any advantage or specific reason someone would do this? Why not just leave it as defaultint? --------------Solutio

  • uint.MaxValue in .NET 2009-02-08

    uint x = uint.MaxValue - 100; The above line causes visual studio to report "The operation overflows at compile time in checked mode" I'm obviously missing something. Any ideas what? --------------Solutions------------- this error is being reported b

  • Why does "int[] is uint[] == true" in C# 2009-02-27

    Can somebody clarify the C# is keyword please. In particular these 2 questions: Q1) line 5; Why does this return true? Q2) line 7; Why no cast exception? public void Test() { object intArray = new int[] { -100, -200 }; if (intArray is uint[]) //why d

  • hash function providing unique uint from an integer coordinate pair 2009-03-25

    The problem in general: I have a big 2d point space, sparsely populated with dots. Think of it as a big white canvas sprinkled with black dots. I have to iterate over and search through these dots a lot. The Canvas (point space) can be huge, borderin

  • AS3: declaring an "undefined" parameter for int, uint or Number 2009-05-08

    I'd like to implement the following logic: function setMyValue (myVar:int = undefined):void { if (myVar == undefined) { /* Generate a value for myVar */ } else { /* Use the supplied value for myVar */ } } So if the value is supplied, use it. If not,

  • How to pass uint in Java? 2009-05-09

    I'm trying to call SendMessage with an uint parameter from Java, but I can't convert int to uint. I can't change the uint parameter in SendMessage because it is a windows function. Is there some way of doing this? Background: I'm actually using Proce

  • Why does a compiler dislike implicitly casting to uint's? 2009-05-13

    I have run into a couple of similar quirks regarding uint usage in both C++ and C#, and now I'm wondering on the reasoning (which may be completely different for each example). For both of these examples, note that I am compiling with the warning lev

  • Why can't I pull a ushort from a System.Object and then cast it as a uint? (C#) 2009-07-03

    I'm manipulating the items in a list that's a System.Management.ManagementObjectCollection. Each of these items is a System.Management.ManagementObject which contains properties indexed by string. See: foreach (ManagementObject queryObj in searcher.G

  • How do I convert uint to int in C#? 2009-07-15

    How do I convert uint to int in C#? --------------Solutions------------- Given: uint n = 3; int i = checked((int)n); //throws OverflowException if n > Int32.MaxValue int i = unchecked((int)n); //converts the bits only //i will be negative if n

Copyright (C), All Rights Reserved.

processed in 0.107 (s). 11 q(s)