C#: Check if type T is bool

c#, compiler-errors

Solution

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):

public static T GetValue<T>(T defaultValue)
{
  // Need to use typeof to get a Type object for bool, just as with T
  if (typeof(T) == typeof(bool)) {
    // Need to say "get out of my way C#"
    // The first cast to object is required as true (bool) is
    // otherwise not castable to an unrestricted T.
    // This widen-restrict approach could result in a cast error,
    // but from the above check it is known that T is bool.
    return (T)(object)true;
  }
  // .. other stuff that .. does stuff.
}

However, explicitly returning `true` (which is not the default value for a boolean) and ignoring `defaultValue` entirely otherwise seems .. suspect. But - It compiles! Ship it!

Notes:

- The use `==` for Types will not work reliably for subclasses (but it's okay because `bool` is a structure so subtypes are not an issue). In those cases, look at `IsAssignableFrom`.

- `typeof(T)` is not necessarily the type of the value passed in (which could be `null` for reference types). This, along with subtypes, can lead to subtle variations to approaches that use `is` on the value.

Problem

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!

Original source