Home > other >  C# what does (bool ? string : string) do?
C# what does (bool ? string : string) do?

Time:10-06

Looking for help working out what the code in return does / is called

string MakeOrderKey(string s1, string s2)
    {
        bool b = (string.Compare(s1, s2) < 0);
        return ((b ? s1 : s2)  
            "/"  
            (b ? s2 : s1)
            );
    }

CodePudding user response:

it's equivalent to

if (b)
{
     return s1;
}
else
{
     return s2;
}

Edit: As Alexey pointed out, I should clarify. return here isn't the return from your specific function it's just saying that the statement (b ? s1 : s2) will evaluate to either s1 or s2 based on the value of b.

Learn more here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator

CodePudding user response:

It's comparing the strings represented by s1 and s2 and returns a string like "bar/foo" in the comparative order of the strings.

Note that string.Compare may have issues with casing and special characters, consider using string.CompareOrdinal instead.

  •  Tags:  
  • c#
  • Related