How to define a common type limit for primitive types?

I have the following method with a generic type:

T GetValue<T>(); 

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

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

I'm not sure if this is possible for primitive types and how to do it.

+48
generics c # type-constraints
Apr 30 '09 at 3:42
source share
5 answers

You can use this to restrict it to type values:

 where C: struct 

You also specify a string. Unfortunately, strings will not be allowed, as they are not value types.

+38
Apr 30 '09 at 3:47
source share

This actually does the job to a certain extent:

 public T Object<T>() where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T> 

To limit the number types, you can get helpful hints for the following patterns defined for the ValueType class

+14
Dec 03 '13 at
source share

which you are looking for:

 T GetObject<T> where T: struct; 
+12
Apr 30 '09 at 3:48
source share

There is no general restriction that would fit this set of things cleanly. What do you really want to do? For example, you can crack it with runtime checks like static ctor (for generic types - not so easy for generic methods) ...

However; more often than not, I see this because people want one of:

  • to be able to check elements for equality: in this case use EqualityComparer<T>.Default
  • to be able to compare / sort items: in this case use Comparer<T>.Default
  • to be able to do arithmetic: in this case use MiscUtil support for common operators
+8
Apr 30 '09 at 4:26
source share

What are you really trying to do in a method? Perhaps you really need C to implement IComparable or another interface. In this case, you need something like

 T GetObject<T> where T: IComparable 
+5
Apr 30 '09 at 3:58
source share



All Articles