Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# switch with types

EDIT: This is now available in C# 7.0.


I have the following piece of code that checks a given PropertyInfo's 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 a switch statement 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 don't think this is the best solution, because now I have to give the fully qualified String value of the given type. Any tips?

like image 674
budi Avatar asked Dec 17 '15 23:12

budi


1 Answers

This is now available in C# 7.0.

This solution is for my original question; switch statements work on the value of the PropertyInfo and not its 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;
}

Slightly more generic 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));
}

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

like image 183
budi Avatar answered Nov 04 '22 14:11

budi