Search code examples
c#dictionarymethodstypeslookup-tables

Look-up table in C# with Types and Actions


I want to change my many if to a look-up table.

I have types and methods. I want to pair them.

if (propertyType == typeof(bool) || propertyType == typeof(bool?))
DoBool(propertyType);

if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
DoDateTime(propertyType);

if (propertyType == typeof(Guid) || propertyType == typeof(Guid?))
DoGuid(propertyType);

I have to create a Dictionary<Type, Action>()? Or which is the best elegant way to do this?

Can you offer me some suggestion where can I start or where can I find the solution?


Solution

  • I created my own implementation which is little bit different, but I used @DaggeJ suggestion, so thanks!

    First I created a base handler class. After that I used this base on different type classes. You can see it below.

    BaseClass:

    public abstract class QueryHandler<T> where T : class
    {
        //I added here more property. 
    
        public abstract Type[] Types { get; }
    
        protected QueryHandler(//Properties)
        {
            //Properties null check
        }
    
        public abstract IQueryable<T> Handle();
    }
    

    Descendant class:

    internal class GuidQuery<T> : QueryHandler<T> where T : class
    {
        public override Type[] Types => new Type[] { typeof(Guid), typeof(Guid?) };
    
        public GuidQuery(//Properties) : base(//Properties)
        {
        }
    
        public override IQueryable<T> Handle()
        {
            // Implementation
        }
    }
    

    Usage:

    public IQueryable<T> GetQuery()
    {
        var queryHandlerList = new List<QueryHandler<T>>()
        {
            new IntQuery<T>(//Properties),
            new DateTimeQuery<T>(//Properties),
            new StringQuery<T>(//Properties),
            new BoolQuery<T>(//Properties),
            new GuidQuery<T>(//Properties),
            new EnumQuery<T>(//Properties)
        };
    }
    
    return query = queryHandlerList.FirstOrDefault(h => GetType<T>(h, property.PropertyType)).Handle();
    
    private bool GetType<T>(QueryHandler<T> handler, Type type) where T: class
    {
        if (handler.Types.FirstOrDefault(t => t == type) == type || handler.Types.FirstOrDefault(t => t == type.BaseType) == type.BaseType) return true;
    
        return false;
    }