Detect MaxValue of generic parameter

c#, constraints, generics

Solution

One way would be to leverage the new `dynamic` keyword:

void Main()
{
    Test(10);
    Test(10.234);
    Test((Byte)42);
    Test(true);
}

public void Test<T>(T value)
    where T : struct
{
    T maxValue = MaxValue((dynamic)value);
    maxValue.Dump();
}

public int MaxValue(int dummy)
{
    return int.MaxValue;
}

public double MaxValue(double dummy)
{
    return double.MaxValue;
}

public byte MaxValue(byte dummy)
{
    return byte.MaxValue;
}

public object MaxValue(object dummy)
{
    // This method will catch all types that has no specific method
    throw new NotSupportedException(dummy.GetType().Name);
}

Or, you could use reflection to obtain the MaxValue field:

void Main()
{
    Test(10);
    Test(10.234);
    Test((Byte)42);
    Test(true);
}

public void Test<T>(T value)
    where T : struct
{
    FieldInfo maxValueField = typeof(T).GetField("MaxValue", BindingFlags.Public
        | BindingFlags.Static);
    if (maxValueField == null)
        throw new NotSupportedException(typeof(T).Name);
    T maxValue = (T)maxValueField.GetValue(null);
    maxValue.Dump();
}

You can test these two programs through LINQPad.

Problem

I want to write generic class which should work with `byte` and `ushort` types. What constraint should I use for this class? How can I detect `MaxValue` property inside of this class? ``` class MyClass<T> // where T: ??? { void Foo() { int maxValue = T.MaxValue; // how can I do this? } } ``` If class was created with unexpected type, which doesn't contain MaxValue property, I don't care - for example, I can throw exception at runtime.

Original source

Related problems