0

I have the following method:

void Test<T>(T Result)

and I need to implement something like this:

if Result is null, or T is a bool and that bool is false

I tried to do something like

if (typeof(T) == typeof(bool)
{
  if ((bool)Result == false)   // doesn't work
  if (Result as bool == false) // doesn't work

how can I implement this without creating two methods?

Thomas
  • 10,933
  • 14
  • 65
  • 136

3 Answers3

2

You can try casting it to a nullable bool and test it:

public void Test<T>(T result)
{
    var asBool = result as bool?;
    if (!asBool.HasValue || !asBool.Value)
    {
        // do whatever
    }
}

(I changed Result to result since it is a parameter)

oerkelens
  • 5,053
  • 1
  • 22
  • 29
0

Here's another solution which casts T to bool via object (you can't cast T to bool directly):

if ((bool)(object)result == false)
{
    // bool with value set to false
}

You might also want to consider benchmarking all solutions proposed in the answers if performance is a concern—see "Performance surprise with “as” and nullable types".

trashr0x
  • 6,457
  • 2
  • 29
  • 39
0

You can test with

if (EqualityComparer<T>.Default.Equals(result, default(T))) {
    ...
}

For bool, default(T) is false, for reference types it is null. For all other types, it is a value represented by all bits set to 0. I.e. for numeric types it will be 0.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188