John K John K - 2 months ago 7
C# Question

Writing of if-statement

I'm just wondering, I found on some sites if-statement written this way

if (x == "a") { y = 1; }
else if (x == "b") { y = 2; }
else if (x == "c") { y = 3; }
else if (x == "d") { y = 4; }
else if (x == "e") { y = 5; }
else if (x == "f") { y = 6; }
else if (x == "g") { y = 7; }
else { y = 8; }


is there any difference for code if usually should be:

if (x == "a")
{
y = 1;
}
else if (x == "b")
{
y = 2;
}
else
{
y = 3;
}

Answer

I can say that there is no difference in the given snippets. but you can use switch instead for long if..elseif ladder. for a faster execution. you can try this method Found in this answer, for this scenario.

static int TextToNumber(string text) 
{
    return text
        .Select(c => c - 'a' + 1)
        .Aggregate((sum, next) => sum*26 + next);
}

and the call will be like the following:

y=TextToNumber(x);

If so there is no need for conditional checking and assigning values to y, the method call will return and assign values to the variable y.