2

I would like to limit the data types my method accepts using generics to built in types:

Built in types: http://msdn.microsoft.com/en-us/library/ya5y69ds(v=vs.80).aspx

The list differs from value / reference types. And I would like to only support built in, not all value types, and ofc also string, which is a reference type.

Is this possible?

EDIT:

Using constraints you can restrict to value types like this:

T GetObject<T> where T: struct;

This would not permit strings to pass through though.

JL.
  • 78,954
  • 126
  • 311
  • 459

2 Answers2

2

It's not possible to do with generics.

If you need to do this and retain compile-time checking your only option is to provide overloads of your method with different parameter types so that all the built-in types are covered.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

No, unfortunately it isn't possible.

The closest I think you could do is below:

T GetObject<T>()
{
    if (!(typeof(T) is typeof(int)
        || typeof(T) is typeof(uint)
        ...
        || typeof(T) is typeof(string)))
    {
        //Custom exception class for this purpose
        throw new TypeArgumentException("Invalid type parameter \"T\".");
    }

    ...
}

Not quite as nice, but does the job.

Darkzaelus
  • 2,059
  • 1
  • 15
  • 31