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.
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.
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");
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]();
}
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With