Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast value type to generic

Tags:

c#

generics

I have a generic class that I need to constrain to only value types (int, float, etc.). I have a method that calls the Parse method based on a test of the type. For example:

class MyClass<T>
{
    ...

    private static T ParseEntry(string entry)
    {
        if(typeof(T) == typeof(float))
        {
            return (T) float.Parse(entry);
        }

        if(typeof(T) == typeof(int))
        {
            .... you get the idea
        }
    }
}

Constraining T to struct doesn't work and I really want to avoid boxing/unboxing if possible. Any ideas?

EDIT: To give a little more insight into this. I noticed in a library I'm developing that two classes had very similar properties/methods etc. the only difference was the underlying type of data (int or float). THis lead me to a design with generics. The only hangup is because of the call to the specific Parse method depending on if it's a float or int. I could get around it with boxing/unboxing but I really wanted to avoid that if possible.

like image 547
Brian Triplett Avatar asked May 08 '26 09:05

Brian Triplett


1 Answers

private static T ParseEntry(string entry)
{
    TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
    return (T) conv.ConvertFromString(entry);
}

which has the advantage of working with any type with a type-converter (or you can add your own at runtime). It does have boxing, but really, it isn't so bad. If that is your biggest problem, then you're going about this the wrong way.

like image 168
Marc Gravell Avatar answered May 10 '26 07:05

Marc Gravell