Variable declarations following if statements

后端 未结 4 579
甜味超标
甜味超标 2020-11-28 11:29

An issue came up on another forum and I knew how to fix it, but it revealed a feature of the compiler peculiar to me. The person was getting the error \"Embedded statement c

4条回答
  •  醉梦人生
    2020-11-28 12:15

    When you don't include the brackets, it executes the next line as if it were surrounded by brackets. Since it doesn't make much sense to declare a variable in that line (you wouldn't be able to use it ever), the C# compiler will not allow this to prevent you from accidentally doing it without knowing (which might introduce subtle bugs).

    Here's part of Eric Lippert has to say about the C# compiler on this SO answer about name resolution:

    ...C# is not a "guess what the user meant" language...the compiler by design complains loudly if the best match is something that doesn't work

提交回复
热议问题