tags:

views:

66

answers:

4

Is it possible to constrain a generic method on specific types?

I want to write something like this:

public T GetValue<T>(string _attributeValue) where T : float, string
{
    return default(T); // do some other stuff in reality
}

I'm mostly just trying to avoid having a giant switch statement inside the method or having to throw an exception if an invalid type is specified.

Edit: Ack. I knew string is not a value type. I started out with two numeric types earlier. Sorry.

+2  A: 

This is not possible to do with compile time support. You can do this check in the static constructor and throw an exception (in the case the T is defined on the type) or (in your case) in the method body itself, but in that case it would be a runtime validation.

Steven
+1  A: 

No, you can not specify a range of types. If you want all primatives you can do (and i know string is not included)

 where T: struct
Nix
Don't confuse `value types` (structs) with primitives. Primitives are only the types: `char`, `byte`, `sbyte`, `bool`, `int`, `long`, `uint`, `ulong`, `short`, `ushort`, `float`, and `double`. These are the types that can be represented by literal string values in the language ... interestingly `decimal` does not seem to be considered a primitive type...
LBushkin
+2  A: 

No, it's not possible.

And string is a reference type, not a value type.

The closest you can get is constraining on all value types (minus Nullable types):

public T GetValue<T>(string _attributeValue) where T : struct

Depending on what you're actually doing inside the method, there may be various ways to achieve your goal (other than switch/case). Consider changing your example to be a little more meaningful...

One other option might also be to make your method private and provide public wrappers that are specific:

private T GetValue<T>(string _attributeValue) where T : struct
{
    return default(T);
}

public float GetFloatValue(string _attributeValue)
{
    return GetValue<float>(_attributeValue);
}

public int GetIntValue(string _attributeValue)
{
    return GetValue<int>(_attributeValue);
}

That would allow you to constrain the public members of your class to the desired types but still use generic code internally so you don't have to repeat yourself.

Justin Niessner
+4  A: 

You can't use generic constraints to express the limitations you are interested in. Generics are not meant to express variation based on disjoint types - they're meant to express variation that is unified over a hierarchy of types (or those implementing certain interfaces).

You have a few alternative choices, however. Which you choose depends on the exact nature of what you're trying to do.

Use differently named methods to express each operation. I tend to use this approach when each method is truly doing something different. You could argue that returning a different type of value from a method is essentially a different operation, and deserves its own unique name.

float GetFloat(string attrName) { }
string GetString(string attrName) { }

Provide a "default value" to allow the type to be inferred. In many designs where you ask for a value by name it useful to supply a default value. This can allow you to employ overloading to differentiate between which method to invoke (based on the type of the default value). Unfortunately, this approach is quite fragile - and breaks easily when passing literal values to overloads that accept numeric primitives (int vs. uint vs. long).

float GetValue(string attrName, float defaultValue) { ... }
string GetValue(string attrName, string defaultValue) { ... }

Use a generic method, but throw a runtime exception if the type isn't one of those you support. Personally I find this kind of ugly and in violation of the spirit of generics - generics should unify functionality over a hierarchy or a set of types implementing some interface. However, in some cases it makes sense to do so (if let's so one specific type cannot be supported, let's say). Another problem with this approach is that the signature of the generic method cannot be inferred from any parameters, so you would have to specify the type desired when calling it ... at which point it's not much better (from a syntax point of view) than having different method names.

T GetValue<T>( string attrName )
{
   if( typeof(T) != typeof(string) ||
       typeof(T) != typeof(float) )
       throw new NotSupportedException();
   return default(T); 
}

// call it by specifying the type expected...
float f = GetValue<float>(attrName);
string s = GetValue<string>(attrName);

Use an out parameter instead of a return value. This approach works well, but it loses the concise syntax of being able to call a method and act on a return value, since you first have to declare a variable to populate.

void GetValue( string attrName, out float value )
void GetValue( string attrName, out string value )

// example of usage:
float f;
GetValue( attrName, out f );
string s;
GetValue( attrName, out s );
LBushkin