Lunatiic Lunatiic - 10 months ago 58
C# Question

if (string) vs if (bool) in C#

Is there a noticeable difference in performance/code quality if you use a string to compare at the start of an "if" instead of a boolean?

Example with string:

string isTrue = "true";
if (isTrue == "true"){
// do something

Example with bool:

bool isTrue = true;
if (isTrue){
//do something

I generally use a bool for these kind of comparisons but I've seen both variations online.

Answer Source

Based on code generated on tryroslyn


using System;
public class C {
    public void M() {
        string isStringTrue = "true";
        if (isStringTrue == "true")
            // do something

        bool isBoolTrue = true;
        if (isBoolTrue)
            //do something

Produce IL code:

.class private auto ansi '<Module>'
} // end of class <Module>

.class public auto ansi beforefieldinit C
    extends [mscorlib]System.Object
    // Methods
    .method public hidebysig 
        instance void M () cil managed 
        // Method begins at RVA 0x2050
        // Code size 34 (0x22)
        .maxstack 2
        .locals init (
            [0] string,
            [1] bool,
            [2] bool,
            [3] bool

        IL_0000: nop
        IL_0001: ldstr "true"
        IL_0006: stloc.0
        IL_0007: ldloc.0
        IL_0008: ldstr "true"
        IL_000d: call bool [mscorlib]System.String::op_Equality(string, string)
        IL_0012: stloc.2
        IL_0013: ldloc.2
        IL_0014: brfalse.s IL_0018
        IL_0016: nop
        IL_0017: nop
        IL_0018: ldc.i4.1
        IL_0019: stloc.1
        IL_001a: ldloc.1
        IL_001b: stloc.3
        IL_001c: ldloc.3
        IL_001d: brfalse.s IL_0021
        IL_001f: nop
        IL_0020: nop
        IL_0021: ret
    } // end of method C::M

    .method public hidebysig specialname rtspecialname 
        instance void .ctor () cil managed 
        // Method begins at RVA 0x207e
        // Code size 8 (0x8)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: call instance void [mscorlib]System.Object::.ctor()
        IL_0006: nop
        IL_0007: ret
    } // end of method C::.ctor

} // end of class C

As you can see compare strings needs call method, compare bools don't need this.