Reputation: 1122
In generic method I have to do different actions for each Type. I do it so:
public static T Foo<T>(string parameter)
{
switch (typeof(T).Name)
{
case "Int32":
...
break;
case "String":
...
break;
case "Guid":
...
break;
case "Decimal":
...
break;
}
}
Is there better way to know Type T? if (T is int) does not work.
Upvotes: 0
Views: 100
Reputation: 39610
How about this:
switch (Type.GetTypeCode(typeof(T))) {
case TypeCode.Int32:
break;
case TypeCode.String:
break;
}
This only works for the basic types defined in the TypeCode
enumeration though (which don't include Guid
). For other cases, if (typeof(T) == typeof(whatever)
) is another good way to check types.
Upvotes: 0
Reputation: 45101
Create a Dictionary<Type, Action<object>
:
class TypeDispatcher
{
private Dictionary<Type, Action<object>> _TypeDispatchers;
public TypeDispatcher()
{
_TypeDispatchers = new Dictionary<Type, Action<object>>();
// Add a method as lambda.
_TypeDispatchers.Add(typeof(String), obj => Console.WriteLine((String)obj));
// Add a method within the class.
_TypeDispatchers.Add(typeof(int), MyInt32Action);
}
private void MyInt32Action(object value)
{
// We can safely cast it, cause the dictionary
// ensures that we only get integers.
var integer = (int)value;
Console.WriteLine("Multiply by two: " + (integer * 2));
}
public void BringTheAction(object value)
{
Action<object> action;
var valueType = value.GetType();
// Check if we have something for this type to do.
if (!_TypeDispatchers.TryGetValue(valueType, out action))
{
Console.WriteLine("Unknown type: " + valueType.FullName);
}
else
{
action(value);
}
}
This can then by called by:
var typeDispatcher = new TypeDispatcher();
typeDispatcher.BringTheAction("Hello World");
typeDispatcher.BringTheAction(42);
typeDispatcher.BringTheAction(DateTime.Now);
Upvotes: 0
Reputation: 174319
It would be better to use if
in combination with typeof(<the type to test for>)
:
if(typeof(T) == typeof(int))
{
// Foo has been called with int as parameter: Foo<int>(...)
}
else if(typeof(T) == typeof(string))
{
// Foo has been called with string as parameter: Foo<string>(...)
}
Upvotes: 2