Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch over PropertyType

How can I make this work?

switch(property.PropertyType){
    case typeof(Boolean): 
        //doStuff
        break;
    case typeof(String): 
        //doOtherStuff
        break;
    default: break;
}

I don't want to use the name since string comparing for types is just awfull and can be subject to change.

like image 285
Boris Callens Avatar asked Sep 18 '08 10:09

Boris Callens


4 Answers

        System.Type propertyType = typeof(Boolean);
        System.TypeCode typeCode = Type.GetTypeCode(propertyType);
        switch (typeCode)
        {
            case TypeCode.Boolean:
                //doStuff
                break;
            case TypeCode.String:
                //doOtherStuff
                break;
            default: break;
        }

You can use an hybrid approach for TypeCode.Object where you dynamic if with typeof. This is very fast because for the first part - the switch - the compiler can decide based on a lookup table.

like image 75
Jorge Ferreira Avatar answered Nov 14 '22 10:11

Jorge Ferreira


You can't. What you can do is create a mapping between Types and a delegate using a dictionary:

var TypeMapping = new Dictionary<Type, Action<string>>(){
    {typeof(string), (x)=>Console.WriteLine("string")},
    {typeof(bool), (x)=>Console.WriteLine("bool")}
};



string s = "my string";

TypeMapping[s.GetType()]("foo");
TypeMapping[true.GetType()]("true");
like image 37
Paul van Brenk Avatar answered Nov 14 '22 10:11

Paul van Brenk


I think what you are looking for here is a good Map. Using delegates and a Generic IDictionary you can do what you want.

Try something like this:

private delegate object MyDelegate();

private IDictionary<Type, MyDelegate> functionMap = new IDictionary<Type, MyDelegate>();

public Init()
{
  functionMap.Add(typeof(String), someFunction);
  functionMap.Add(tyepof(Boolean), someOtherFunction);
}

public T doStuff<T>(Type someType)
{
   return (T)functionMap[someType]();
}
like image 2
Josh Avatar answered Nov 14 '22 08:11

Josh


C# 7.0 will support switch on types as a part of bigger pattern matching feature. This example is taken from .NET blog post that announces new features:

switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}
like image 2
Krzysztof Branicki Avatar answered Nov 14 '22 08:11

Krzysztof Branicki