C # switch with types

EDIT: Now it is available in C # 7.0.


I have the following code snippet that validates a given PropertyInfo type .

 PropertyInfo prop; // init prop, etc... if (typeof(String).IsAssignableFrom(prop.PropertyType)) { // ... } else if (typeof(Int32).IsAssignableFrom(prop.PropertyType)) { // ... } else if (typeof(DateTime).IsAssignableFrom(prop.PropertyType)) { // ... } 

Is there a way to use the switch in this scenario? This is my current solution:

 switch (prop.PropertyType.ToString()) { case "System.String": // ... break; case "System.Int32": // ... break; case "System.DateTime": // ... break; default: // ... break; } 

I do not think this is the best solution, because now I have to give the full String value of this type . Any tips?

+7
reflection c # switch-statement
source share
6 answers

I will definitely answer the question: "No."

switch with C # 6 only supports constant matching of certain types. You are not trying to match constants. You call the IsAssignableFrom method many times.

Note that IsAssignableFrom does not exactly match the corresponding types. Therefore, any solution based on equality comparison or hash tables cannot work.

I think the if ... else if solution you have is completely fine.

+4
source share

Now it is available in C # 7.0.

This is the solution to my initial question; The switch work with value PropertyInfo , not with PropertyType :

 PropertyInfo prop; // init prop, etc... var value = prop.GetValue(null); switch (value) { case string s: // ... break; case int i: // ... break; case DateTime d: // ... break; default: // ... break; } 

A slightly more general answer:

 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)); } 

Link: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

+6
source share

There is no general way, but more often than not, these branches contain very similar code. One pattern that almost always works for me is to use a dictionary;

 var myIndex = new Dictionary<Type, string> { { typeof(string), "some text" }, { typeof(int), "a whole number" }, { typeof(decimal), "a fraction" }, }; string description; if (myIndex.TryGetValue(prop.PropertyType, out description)) { Console.WriteLine("This type is " + description); } else { // 'default' } 
+3
source share

Use the ToString method you have, but use case typeof (string) instead of literal values. The name (if possible) does not have vs in front of me right now.

+1
source share

First of all, IsAssignableFrom better than just comparing strings in the case of inherited types. For example, typeof(TextReader).IsAssignableFrom(typeof(StreamReader)) will be true because the StreamReader inherited from TextReader also works for interfaces.

If you need only a direct comparison, I can suggest creating a Dictionary<Type,Action<PropertyInfo>> , for example:

 var typeSelector = new Dictionary<Type, Action<PropertyInfo>>() { {typeof(int), IntAction } {typeof(string), StringAction } {typeof(DateTime), DateTimeAction } }; 

Then you can use it as follows:

 Action<PropertyInfo> action; if (typeSelector.TryGetValue(prop.PropertyType, out action)) action(prop); else throw new InvalidDataException("Unsupported type"); 

Of course, in this case you will have to create a method for each type or write code during the creation of the dictionary.

+1
source share

As shown in Mårten Wikström, answer: “ How do I use a toggle key on a type? ” You can use Type.GetTypeCode as such:

 switch (Type.GetTypeCode(type)) { case TypeCode.Int32: // It an int break; case TypeCode.String: // It a string break; // Other type code cases here... default: // Fallback to using if-else statements... if (type == typeof(MyCoolType)) { // ... } else if (type == typeof(MyOtherType)) { // ... } // etc... } 
0
source share

All Articles