开发者

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

This question already has answers here: Closed 12 years ago.
开发者_运维技巧

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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜