I can’t believe I can’t google this. I don’t know what to google.
public static T GetValue<T>(T defaultValue)
{
if (T is bool) // <-- what is the correct syntax here?
return (T)true; // <-- I don't think this works either
}
EDIT: Sorry I didn’t mention, the function above is only to show my question. It’s not a real function. Thanks everyone for the answers!
If one must use this same method/signature and must use the type of
T(and there are reason for such, although if there are not then see Albin’s answer):However, explicitly returning
true(which is not the default value for a boolean) and ignoringdefaultValueentirely otherwise seems .. suspect. But – It compiles! Ship it!Notes:
==for Types will not work reliably for subclasses (but it’s okay becauseboolis a structure so subtypes are not an issue). In those cases, look atIsAssignableFrom.typeof(T)is not necessarily the type of the value passed in (which could benullfor reference types). This, along with subtypes, can lead to subtle variations to approaches that useison the value.