Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I allow a method to accept either a string or int?

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?

like image 789
user390480 Avatar asked Nov 28 '22 18:11

user390480


2 Answers

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.

like image 168
Cody Gray Avatar answered Feb 07 '23 09:02

Cody Gray


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
        }
    }
like image 40
Bebben Avatar answered Feb 07 '23 10:02

Bebben