views:

1438

answers:

4

I have the following method with generic type:

T GetValue<T>();

I would like to limit T to primitive types such as int, string, float but not class type. I know I can define generic for class type like this:

C GetObject<C>() where C: class;

I am not sure if it is possible for primitive types and how if so.

+5  A: 

Use this:

where C: struct

That will limit it to value types.

EDIT: I just noticed you also mention string. Unfortunatley, strings won't be allowed as they are not value types.

BFree
but not for string which is nullable
David.Chu.ca
And of course it lets you pass any user-defined struct type, not just primitive types. I'm not sure there's a way, really, other than defining overloads for all the built-in primitive types.
Matt Hamilton
+3  A: 

you're looking for:

T GetObject<T> where T: struct;
Joshua Belden
Dang it! I hate when someone beats me to the punch. Nice BFree!
Joshua Belden
how about string which is primitive but nullable type
David.Chu.ca
@David: string isn't a primitive type. It's a reference type that in some cases is treated as a primitive type.
Samuel
+1  A: 

What are you actually trying to do in the method? It could be that you actually need C to implement IComparable, or someother interface. In which case you want something like

T GetObject<T> where T: IComparable
David McEwing
+2  A: 

There is no generic constraint that matches that set of things cleanly. What is it that you actually want to do? For example, you can hack around it with runtime checks, such as a static ctor (for generic types - not so easy for generic methods)...

However; most times I see this, it is because people want one of:

  • to be able to check items for equality: in which case use EqualityComparer<T>.Default
  • to be able to compare/sort items: in which case use Comparer<T>.Default
  • to be able to perform arithmetic: in which case use MiscUtil's support for generic operators
Marc Gravell