In C# should I use uint or int for values that are never supposed to be negative? [duplicate]

StackOverflow https://stackoverflow.com/questions/2963057

문제

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?) that some value may never be negative. However, int is more common, and a cast is often inconvenient. One can just use int and always supplement it with code contracts (everyone has moved to .Net 4.0 by now, right?) Standard libraries do use int for Length and Size properties, even though those should never be negative. So, is it obvious to you that int is better than uint most of the time, or is it more complicated?

Please ask questions if you find that this question is not clearly stated.

Thanks.

EDIT: Yup, looks like a dupe. However, and extra small question: could you give me a good example of how to supplement the properties / functions with code contracts / assert statements in this particular case when value may not be negative?

도움이 되었습니까?

해결책

See here for the previous answer.

다른 팁

Short answer is No. You may want to implement as below.

private int _length;
public int Length
{
    get { return _length; }
    set
    {
        if (value < 0)
        {
            throw new InvalidOperationException("Length must be always positive. Please make sure the value is positive value.");
        }
        this._length = value;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top