Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for bool values with generic T

Tags:

c#

generics

I have a generic method which I'd like to pass in either a reference type or bool.

private void Test<T>(T value)
{
    if(typeof(T)) == typeof(bool))
    {
        if(value == false)
            // do something
        else if (value == null)
            // do something else
    }
}

but I'm getting this compile time error "Operator ==' cannot be applied to operands of typeT' and `bool'". Is there a simple solution to this (preferably without using Reflection)?

Update: If it's enclosed in a foreach loop, will there be an implicit cast? I still receive the same compile error.

private void Test<T>(T[] values)
{
    foreach(T value in values)
    {
        if(typeof(T)) == typeof(bool))
        {
            if(value == false)
                // do something
        }
        else if (value == null)
                // do something else
    }
}
like image 441
user2994682 Avatar asked Nov 22 '25 11:11

user2994682


1 Answers

Use the is operator:

private void Test<T>(T value)
{
    if(value is bool)
    {
        ...
    }
}

or the as operator:

private void Test<T>(T value)
{
    bool? boolValue = value as bool;
    if (boolValue != null) {
        // do something with boolValue, which can never be null if value is of type bool
    }
    else {
        // do something with value, which is not a boolean
    }
}
like image 62
mayabelle Avatar answered Nov 25 '25 05:11

mayabelle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!