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.
Unfortunately, you cannot create constraints of the type of describe. You cannot write, for example:
You may be better off leaving the constraint to be
struct, but add some runtime checks to make sure that T is only one of the supported types when you instantiate the class. Since you haven’t said much how you’re planning to use your class – it’s hard to offer alternative design advice on how to achieve better type safety.EDIT: You should look at the type converter option that Marc and others recommend. This seems like the way to go.
EDIT: One possible idea that occurs to me, is to make the
Parse()method actually be a delegate:Func<string,T>– that you assign during construction. This would make it possible for you to:Here’s a code example of what I mean:
You can read about the available constraints here. The only constraints available are: