OK, here we go again! Following on from my previous question on Converting to a Generic Type from String, I thought I would ask another Generics-related question!
This time, is there a way to enforce/limit the types that are passed to PRIMITIVE's? (bool, int, string, etc)
Now, I know you can limit the generic type parameter to a type or interface implementation via the where clause, however, this doesn't fit the bill for primitives (AFAIK) because the do not all have common ground (apart from object before someone says! :P).
So, my current thoughts are to just grit my teeth and do a big switch statement and throw an ArgumentException on failure..
Just thought I would check here to see if the awesome pool of wisdom that is StackOverflow could offer any better ideas? :)
Many thanks.
EDIT Just to clarify:
The code definition should be like:
public class MyClass<GenericType> ....
And instantiation:
MyClass<bool> = new MyClass<bool>(); // Legal
MyClass<string> = new MyClass<string>(); // Legal
MyClass<DataSet> = new MyClass<DataSet>(); // Illegal
MyClass<RobsFunkyHat> = new MyClass<RobsFunkyHat>(); // Illegal (but looks awesome!)
EDIT: This was so simple following on from Jon Limjaps Pointer.. So simple I almost want to cry, but it's great because the code works like a charm!
So here is what I did (you'll laugh!):
Code Added to the Generic Class
bool TypeValid()
{
// Get the TypeCode from the Primitive Type
TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType));
// All of the TypeCode Enumeration refer Primitive Types
// with the exception of Object and Empty (Null).
// Since I am willing to allow Null Types (at this time)
// all we need to check for is Object!
switch (code)
{
case TypeCode.Object:
return false;
default:
return true;
}
}
Then a little utility method to check the type and throw an Exception...
private void EnforcePrimitiveType()
{
if (!TypeValid())
throw new InvalidOperationException(
"Unable to Instantiate SimpleMetadata based on the Generic Type of '" + typeof(PrimitiveDataType).Name +
"' - this Class is Designed to Work with Primitive Data Types Only.");
}
All that then needs to be done is to call EnforcePrimitiveType() in the classes constructors.. Job done! :)
The only one downside, it only throws an Exception at runtime (obviously) rather than design time.. But thats no big deal and could be picked up with utilities like FxCop (which we don't use at work).
Special thanks to Jon Limjap on this one!