In my code I’ve got a generic, “getProperty” like so:
public T getProperty<T>(int GUID, string property)
{
PropertyComponent prop;
prop = propDict[GUID];
if(property.Equals("visible")) return (T) (Boolean) prop.visible;
if(property.Equals("enabled")) return prop.enabled;
if(property.Equals("position")) return (T) (Object) prop.position;
}
Visual Studio’s compiler gives me no error for the 3rd term, as prop.position is a Vector2. Prop.visible and prop.enabled, however, are bool s, so when I try to return them in this way, I get an error of “Cannot convert type bool to T” (and “Cannot implicitly convert type bool to T” for the 2nd).
What’s the right way to return a bool in this situation?
You can constrain a generic type parameter to be a class or a struct (using where clauses) but in your example you’re treating the T type as both a class and a struct (the bool value type).
If you want to return reference type object instances as well as value type data (like bool), you’re going to have to “box” the value types into objects, as the reference type object is the only common denominator between reference types and value types. Boxing happens automatically when you typecast a value type to Object. So, all your return values should be typecast to
(T)(object).