Stefan Bormann
Stefan Bormann

Reputation: 693

How to find out if a numeric type is signed or unsigned in C#

I want to know details about the type of a field by reflection.

I know I can find out that it is a value type with Type.IsValueType. But from there how do I know it is a number? A fixed point number? Signed or unsigned??

Is there anything like Type.IsSigned?

Upvotes: 5

Views: 1822

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157048

There aren't that many numeric types that are unsigned, so why not compose a list of that:

if (new Type[] { typeof(ushort), typeof(uint), typeof(ulong), typeof(byte) }.Contains(type))
{
    // unsigned.
}

Or if you just want to compare the value (here o):

if (o is ushort || o is uint || o is ulong || o is byte)
{
    // unsigned.
}

Upvotes: 10

Related Questions