Is there a way to enforce/limit the types that are passed to primitives? (bool, int, string, etc.)
Now, I know you can limit the generic typ
public class Class1<GenericType> where GenericType : struct
{
}
This one seemed to do the job..
Use a custom FxCop rule that flags undesirable usage of MyClass<>
.
@Rob, Enum
's will slip through the TypeValid
function as it's TypeCode
is Integer
. I've updated the function to also check for Enum
.
Private Function TypeValid() As Boolean
Dim g As Type = GetType(T)
Dim code As TypeCode = Type.GetTypeCode(g)
' All of the TypeCode Enumeration refer Primitive Types
' with the exception of Object and Empty (Nothing).
' Note: must also catch Enum as its type is Integer.
Select Case code
Case TypeCode.Object
Return False
Case Else
' Enum's TypeCode is Integer, so check BaseType
If g.BaseType Is GetType(System.Enum) Then
Return False
Else
Return True
End If
End Select
End Function
You can simplify the EnforcePrimitiveType
method by using typeof(PrimitiveDataType).IsPrimitive property. Am I missing something?
Primitives appear to be specified in the TypeCode enumeration:
Perhaps there is a way to find out if an object contains the TypeCode enum
without having to cast it to an specific object or call GetType()
or typeof()
?
Update It was right under my nose. The code sample there shows this:
static void WriteObjectInfo(object testObject)
{
TypeCode typeCode = Type.GetTypeCode( testObject.GetType() );
switch( typeCode )
{
case TypeCode.Boolean:
Console.WriteLine("Boolean: {0}", testObject);
break;
case TypeCode.Double:
Console.WriteLine("Double: {0}", testObject);
break;
default:
Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject);
break;
}
}
}
It's still an ugly switch. But it's a good place to start!
Having a similar challenge, I was wondering how you guys felt about the IConvertible interface. It allows what the requester requires, and you can extend with your own implementations.
Example:
public class MyClass<TKey>
where TKey : IConvertible
{
// class intentionally abbreviated
}
I am thinking about this as a solution, all though many of the suggested was part of my selection also.
My concern is - however - is it misleading for potential developers using your class?
Cheers - and thanks.