Search code examples
c#mscorlib

Avoiding calls to mscorlib when comparing strings?


Is there a possible way that let me compare strings without calling the op_Equality function is mscorlib? For example:

string s1 = "hi";
if(s1 == "bye")
{
Console.Writeline("foo");
}

Compiles to:

IL_0003: call bool [mscorlib]System.String::op_Equality(string, string)

And looking at op_Equality at mscorlib from GAC it calls another method Equals(string, string) Code:

public static bool Equals(string a, string b)
{
   return a == b || (a != null && b != null && string.EqualsHelper(a, b));
}

it uses the op code bne.une.s to compare those strings.

Now back at my question, how can I compare 2 strings without calling any function from the mscorlib like the method Equals does.


Solution

  • Now back at my question, how can I compare 2 strings without calling any function from the mscorlib like the method Equals does.

    You can't - at least not without writing your own string comparison method from scratch.

    At some point, you'd have to at least call String.Equals(a,b) (in order to have the private EqualsHelper method called, which does the actual comparison), which is also defined in mscorlib.

    You could call Equals directly if you wish to avoid the operator call, though:

    string s1 = "hi";
    if (string.Equals(s1, "bye"))
    {
        Console.WriteLine("foo");
    }
    

    This would avoid the call to op_Equality, bypassing it and calling Equals directly.

    That being said, there is really no reason to avoid calling op_Equality on strings in the first place...