简体   繁体   中英

Curly brackets vs no curly brackets in lambda expression c#

I am pretty new to C#, around 1 year experience. Recently got introduced to lambda expressions. I want to have an Action<string> which would display an Error with custom Error text to a MessageBox. I am wondering, what is the difference between:

public static Action<string> Error = s => { MessageBox.Show(s, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); };

and

public static Action<string> Error = s => MessageBox.Show(s, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

Thanks for any helpful advises :)

According to official C# language specification:

8.2 Blocks

A block permits multiple statements to be written in contexts where a single statement is allowed.

block:
    {   statement-listopt   }

A block consists of an optional statement-list (§8.2.1), enclosed in braces. If the statement list is omitted, the block is said to be empty.

A block may contain declaration statements (§8.5). The scope of a local variable or constant declared in a block is the block.

Within a block, the meaning of a name used in an expression context must always be the same (§7.6.2.1).

A block is executed as follows:

• If the block is empty, control is transferred to the end point of the block.

• If the block is not empty, control is transferred to the statement list.

When and if control reaches the end point of the statement list, control is transferred to the end point of the block.

The statement list of a block is reachable if the block itself is reachable.

The end point of a block is reachable if the block is empty or if the end point of the statement list is reachable.

The difference is only syntactical, it has no impact on the code that executes. The same thing is compiled using either notation.

After an => , you may either write a block statement, which is surrounded by { and } . You may also write a single expression 'line of code' and omit the curly braces, to prevent boilerplate curly braces.

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