Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Max value of a dynamic type in C#

Tags:

c#

types

I wrote a method in C# which returns Type and based on this type (which is int or long)

private Type GetNumberColumnType(INumberedEntity entity)
{
    var numberRow = SG.Framework.Numbering.NumberingService.NumberableEntities.Where(ne => ne.GetType().FullName == entity.ToString()).FirstOrDefault();
    var row = (DataRow)numberRow;
    return row.Table.Columns[numberRow.NumberColumnName].DataType;
}

I want to get:

GetNumberColumnType(INumberedEntity entity).MaxValue 

instead of:

if( GetNumberColumnType(entity) == typeof(long))
   long.MaxValue
else
   int.MaxValue

What should I do?

like image 784
fasadat Avatar asked Mar 22 '23 03:03

fasadat


1 Answers

If you don't mind using reflection, here's how you go.

var type = GetNumberColumnType(entity);
FieldInfo fi = type.GetField("MaxValue");
if(fi!=null && fi.IsLiteral && !fi.IsInitOnly)
{
    object value = fi.GetRawConstantValue();
}

As noted in comments, reflection is expensive, since these are just constants you can just make a lookup

internal class MaxValueCache
{
    private static readonly Dictionary<Type, object> maxValues = new Dictionary<Type, object>()
    {
        { typeof(int), int.MaxValue},
        { typeof(long), long.MaxValue}
        //...
    };

    public static object GetMaxValue(Type type)
    {
        return maxValues[type];
    }
}

Then use

var type = GetNumberColumnType(entity);
object value = MaxValueCache.GetMaxValue(type);
like image 87
Sriram Sakthivel Avatar answered Apr 06 '23 08:04

Sriram Sakthivel