Using C# 4.0, is there a way to allow a method (without creating an overload) to accept a string or an int and then allow me to detect what type was passed in?
Since you're using C# 4.0, you can write a generic method. For example:
void MyMethod<T>(T param)
{
if (typeof(T) == typeof(int))
{
// the object is an int
}
else if (typeof(T) == typeof(string))
{
// the object is a string
}
}
But you should very seriously consider whether or not this is a good idea. The above example is a bit of a code smell. In fact, the whole point of generics is to be generic. If you have to special-case your code depending on the type of the object passed in, that's a sign you should be using overloading instead. That way, each method overload handles its unique case. I can't imagine any disadvantage to doing so.
Sure you can! An example of this is
public void MyMethod(object o)
{
if (o.GetType() == typeof(string))
{
//Do something if string
}
else if (o.GetType() == typeof(int))
{
// Do something else
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With