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
}
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With