116

I can call Get<int>(Stat); or Get<string>(Name);

But when compiling I get:

Cannot implicitly convert type 'int' to 'T'

and the same thing for string.

public T Get<T>(Stats type) where T : IConvertible
{
    if (typeof(T) == typeof(int))
    {
        int t = Convert.ToInt16(PlayerStats[type]);
        return t;
    }
    if (typeof(T) == typeof(string))
    {
        string t = PlayerStats[type].ToString();
        return t;
    }
}
1
  • 7
    You are probably thinking that the if block checked that T is int, so within the block, you know T is int and you should be able to implicitly convert int to T. But the compiler is not designed to follow that reasoning, it just knows that generally T does not derive from int, so it doesn't allow the implicit conversion. (And if the compiler supported it, the verifier wouldn't, so the compiled assembly would be unverifiable.)
    – JGWeissman
    Nov 17, 2011 at 20:20

8 Answers 8

168

You should be able to just use Convert.ChangeType() instead of your custom code:

public T Get<T>(Stats type) where T : IConvertible
{
    return (T) Convert.ChangeType(PlayerStats[type], typeof(T));
}
4
  • 29
    How about return (T)(object)PlayerStats[type];
    – maxp
    Nov 4, 2015 at 10:06
  • @BrokenGlass Thank you It is working well. Jan 7, 2021 at 9:44
  • @maxp becareful It doesn't work for general purpose, for example casting unmanaged type requires 'Convert.ChangeType()'. Jan 7, 2021 at 9:45
  • 1
    far better than "you shouldn't"
    – Persk
    Mar 29, 2021 at 7:45
143

Any time you find yourself switching on a type in a generic you are almost certainly doing something wrong. Generics should be generic; they should operate identically completely independent of the type.

If T can only be int or string then don't write your code this way at all in the first place. Write two methods, one that returns an int and one that returns a string.

6
  • 1
    Get<Car> where car implements IConvertible will cause breakage. When someone sees you have a generic method they will assume they can pass in anything that implements IConvertible.
    – Tjaart
    Sep 26, 2012 at 5:54
  • 17
    I can only partially agree with you, @Eric .I have a situation where I have to parse arrays stored in XML-tags.The problem is that the specification that the XML document follows(COLLADA in my case) says that such arrays can be not only float,int and bool but also some custom types.However in case you get a float[](array-tags contain the type of stored data in their names:float_array stores floats) you need to parse the string as an array of floats, which requires some IFormatProvider to be used).I obviously cannot use "T.Parse(...)".So for a small subset of cases I need to use such switching. Jul 30, 2013 at 12:55
  • 2
    This answer will keep you out of the rabbit hole. I wanted to make a function generic for int, int?, bool, bool?, string, and it was seemingly impossible.
    – Jess
    Oct 6, 2015 at 18:14
  • This makes a switch on a generic enumerated type practical. Aug 15, 2018 at 14:59
  • 1
    I didn't want to use this as the answer. But he's right. I wanted to check the type and, if a specific one, set a property on it. Solution was to make a method that took a strongly typed parameter.
    – Matt Dawdy
    Sep 11, 2019 at 0:43
21

Actually, you can just convert it to object and then to T.

T var = (T)(object)42;

An example for bool:

public class Program
{
    public static T Foo<T>()
    {
        if(typeof(T) == typeof(bool)) {
            return (T)(object)true;
        }

        return default(T);
    }

    public static void Main()
    {
        bool boolValue = Foo<bool>(); // == true
        string stringValue = Foo<string>(); // == null
    }
}

Sometimes, this behavior is desirable. For instance, when implementing or overriding a generic method from a base class or interface and you want to add some different functionalities based on the T type.

0
12
    public T Get<T>(Stats type) where T : IConvertible
    {
        if (typeof(T) == typeof(int))
        {
            int t = Convert.ToInt16(PlayerStats[type]);
            return (T)(object)t;
        }
        if (typeof(T) == typeof(string))
        {
            string t = PlayerStats[type].ToString();
            return (T)(object)t;
        }
        return (T)(object)PlayerStats[type];
    }
3
  • 2
    return (T) t; because no null checks are necessary.
    – BoltClock
    Nov 17, 2011 at 17:20
  • This above won't compile for me. T needs to be a reference type for "as" to compile. Mar 9, 2018 at 9:21
  • Error CS0030: Cannot convert type 'int' to 'T'
    – palota
    Jan 24 at 12:05
10

Try this:

public T Get<T>(Stats type ) where T : IConvertible
{
    if (typeof(T) == typeof(int))
    {
        return (T)(object)Convert.ToInt16(PlayerStats[type]);

    }
    if (typeof(T) == typeof(string))
    {

        return (T)(object)PlayerStats[type];
    }
}
1
  • Thank you this helped, my need is different. I am write a mock method for an existing static method so that I can test it. Using this osherove.com/blog/2012/7/8/…
    – Esen
    Aug 15, 2016 at 18:52
9

ChangeType is probably your best option. My solution is similar to the one provided by BrokenGlass with a bit of try catch logic.

static void Main(string[] args)
{
    object number = "1";
    bool hasConverted;
    var convertedValue = DoConvert<int>(number, out hasConverted);

    Console.WriteLine(hasConverted);
    Console.WriteLine(convertedValue);
}

public static TConvertType DoConvert<TConvertType>(object convertValue, out bool hasConverted)
{
    hasConverted = false;
    var converted = default(TConvertType);
    try
    {
        converted = (TConvertType) 
            Convert.ChangeType(convertValue, typeof(TConvertType));
        hasConverted = true;
    }
    catch (InvalidCastException)
    {
    }
    catch (ArgumentNullException)
    {
    }
    catch (FormatException)
    {
    }
    catch (OverflowException)
    {
    }

    return converted;
}
1
  • My use case is a concrete class derived from a generic abstract class. The class is marked abstract because it defines an abstract method that operates on the generic private member of the base class. The generic uses the C# 7.3 Enum constraint on its generic type. I just successfully completed a test, and it works exactly as I hoped it would. Aug 16, 2018 at 0:24
8

Considering @BrokenGlass logic (Convert.ChangeType) does not support for GUID type.

public T Get<T>(Stats type) where T : IConvertible
{
    return (T) Convert.ChangeType(PlayerStats[type], typeof(T));
}

Error: Invalid cast from 'System.String' to 'System.Guid'.

Instead, use below logic using TypeDescriptor.GetConverter by adding System.ComponentModel namespace.

public T Get<T>(Stats type) where T : IConvertible
{
    (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(PlayerStats[type])
}

Read this.

4

It looks like you need a TypeConverter, see this blog entry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.