Joel
Joel

Reputation: 6213

return generic parameter of type and perform operation

Is it possible to perform operations on a generically passed parameter in C#? I created this minimal example to demonstrate a potential usecase.

private T genericFormatterTest<T>(T x)
{
    if (Type.Equals(x, typeof(int)))
    {
        return (int)x * (int)x; //squared
    } else if (Type.Equals(x, typeof(string)))
    {
        return x.ToString()+"\n";
    }
    throw new InvalidCastException(); //or another suitable exception
}
...
int    squared =  genericFormatterTest<int>(5);
string newline =  genericFormatterTest<string>("hello");

Upvotes: 0

Views: 69

Answers (1)

A Friend
A Friend

Reputation: 2750

So.. The following code works and is 'generic'

private T genericFormatterTest<T>(T x)
{
    if (typeof(T) == typeof(int))
    {
        return (T)(object)((int)(object)x * (int)(object)x); //squared
    }
    else
    {
        return (T)(object)(x + "\n");
    }
}

But is this really what you want?

Used samples from this Q&A

Using the same example you could also introduce a constraint on T, but it only slightly (and arguably) reduces how badly it reads:

private T genericFormatterTest<T>(T x) where T: IConvertible
{
    if (typeof(T) == typeof(int))
    {
        return (T)(object)(Convert.ToInt32(x) * Convert.ToInt32(x)); //squared
    }
    else
    {
        return (T)(object)(x + "\n");
    }
}

Upvotes: 2

Related Questions