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.
Andrey Tretyak
source share