You can create a Dictionary<Type, Action<object>> and save the types (return values ββfrom GetType method a together with delegates who execute any code that you want to run for this type.
For example, look at this:
private readonly Dictionary<Type, Action<object>> typeActions = new Dictionary<Type, Action<object>>() { { typeof(int), (a) => { Console.WriteLine(a.ToString() + " is an integer!"); } }, { typeof(float), (a) => { Console.WriteLine(a.ToString() + " is a single-precision floating-point number!"); } } };
This dictionary can then be used elsewhere in your code:
Action<object> action; if (typeActions.TryGetValue(a.GetType(), out action)) { action(a); }
Note that you still have to cast a to the appropriate type inside your actions.
EDIT: as Chris noted correctly, this will not recognize a.GetType() if a belongs to a subclass of the registered type. If you need to enable this, you will have to go through a type hierarchy:
Action<object> action = null; for (Type t = a.GetType(); t = t.BaseType; t != null) { if (typeActions.TryGetValue(t, out action)) { break; } } if (action != null) { action(a); }
If you need to cover common types and / or interfaces, this is also possible, but the code will become more and more complex.
source share