jeudi 17 décembre 2015

C# Switch With Types

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?





Aucun commentaire:

Enregistrer un commentaire