views:

94

answers:

4

Is it faster to make a comparison or a cast in C#.Net?
For example:

bool? flag = null;    
...    
if(flag == true)... or if((bool)flag)...  

Also, what is the cost (in memory) of a cast?

+3  A: 

If memory serves the compiler will force you to cast the bool? to a bool before using it in the if statement. You might like the null coalesce operator:

//If flag == null then return false, otherwise return the value of flag.
if (flag ?? false)
Spence
+1 for mentioning ??
juharr
Wow thanks, that helped out a lot.
Richard
A: 

IIRC, Those translate to roughly the same thing. Unless you're doing an absurdly large number of such checks, the difference is unnoticable for any practical purposes.

AllenG
A: 

If a null value in flag means "false" I would use the comparison. The cast is a bad idea, beacuse it will throw an exception if flag is null. To be save you have to test for null before the cast. That means you have to do a comparion and a cast instead of a comparion only.

obivandamme
A: 

The performance difference is negligible.

Also keep in mind that

bool? flag = null;
// ...other code...
if ((bool)flag)
{
}

might throw an InvalidOperationException if flag was not assigned in the code between the variable declaration and the cast.

Willem van Rumpt