简体   繁体   中英

C# Which if is the priority for an else if

I have this specific piece of code in my project:

if (type == 1)
    if (line.StartsWith(user.PadRight(FieldLengths1[0])))
        keep = true;
    else if (type == 2)
        if (line.StartsWith(user.PadRight(FieldLengths2[0])))
            keep = true;

Originally, the indenting was different. The else-if is supposed to to be linked to "if (type == 1)", as the content would suggest. But Visual Studio seems to have changed my indentation to suggest that it is instead linked to the next if (if (line.startswith...))

This could be equivalent to

if (type == 1)
{
    if (line.StartsWith(user.PadRight(FieldLengths1[0])))
        keep = true;
}
else if (type == 2)
{
    if (line.StartsWith(user.PadRight(FieldLengths2[0])))
        keep = true;
}

Or to this:

if (type == 1)
{
    if (line.StartsWith(user.PadRight(FieldLengths1[0])))
        keep = true;
    else if (type == 2)
    {
        if (line.StartsWith(user.PadRight(FieldLengths2[0])))
            keep = true;
    }
}

I would like to know how does the else-if behave without brackets, and what exactly decides which if it would be linked to?

The else keyword is always linked to the closest if .

You should use braces to avoid this confusion.

The C# 5.0 Language Specification states in §8.7.1

An else part is associated with the lexically nearest preceding if that is allowed by the syntax.

Documentation on https://msdn.microsoft.com/en-us/library/aa664812(v=vs.71).aspx says:

pp-conditional:   pp-if-section   pp-elif-sectionsopt   pp-else-sectionopt   pp-endif

So, else keyword is matched greedy to the closest if.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM