GetProperty() to get minimum/maximum value of numbers returns null

55 Views Asked by At

I am trying to write a code that outputs the details of a number type (int, uint, ...) in C# (MinValue, MaxValue, sizeof, name).

This is the code I wrote so far:

Console.WriteLine(new string('-', 120));
Console.WriteLine("{0,-10} {1,-20} {2,40} {3,40}",
    "Type", "Byte(s) of memory", "Min", "Max");
Console.WriteLine(new string('-', 120));
Type[] types = new Type[] {
    typeof(byte),
    typeof(sbyte),
    typeof(int),
    typeof(uint),
    typeof(short),
    typeof(ushort),
    typeof(long),
    typeof(ulong),
    typeof(Int128),
    typeof(UInt128),
    typeof(Half),
    typeof(float),
    typeof(double),
    typeof(decimal),
};

int[] typesSizes = new int[]
{
    sizeof(System.Byte),
    sizeof(sbyte),
    sizeof(int),
    sizeof(uint),
    sizeof(short),
    sizeof(ushort),
    sizeof(long),
    sizeof(ulong),
    sizeof(Int128),
    sizeof(UInt128),
    sizeof(Half),
    sizeof(float),
    sizeof(double),
    sizeof(decimal),
};

dynamic instance;
int size;
Type type;

for (int i = 0; i < typesSizes.Length; i++)
{
    size = typesSizes[i];
    type = types[i];

    instance = Activator.CreateInstance(type);

    if (instance == null)
    {
        throw new NullReferenceException();
    }
    
    var minValue = type.GetProperty("MinValue")?.GetValue(instance);// here it returns null for built-in types
    var maxValue = type.GetProperty("MaxValue")?.GetValue(instance);

    Console.WriteLine("{0,-10} {1,-20} {2,40} {3,40}",
    type.Name, size, minValue, maxValue);
}

I don't know why - but it returns null for the built-in number types.

I know I can solve this problem much easier by just creating 4 arrays and copying pasting the properties. But I want to know why/how this happens.

1

There are 1 best solutions below

0
janw On

Your code is mostly correct, but for primitive integer types, MinValue and MaxValue are (constant) fields, not properties.

So, for int, float etc. it must be GetField instead of GetProperty:

var minValue = type.GetField("MinValue")?.GetValue(instance);
var maxValue = type.GetField("MaxValue")?.GetValue(instance);