Search code examples
c#methodsformattingbraces

Why do methods with only one statement need braces?


public void Finalise()
    ProcessFinalisation(true);

Doesn't compile, but the correct version:

public void Finalise()
{
    ProcessFinalisation(true);
}

Compiles fine (of course).

If I am allowed if's without brackets when the following code has only one line:

if(true)
    CallMethod();

Why is the same not allowed for methods with one following line? Is there a technical reason?


Solution

  • Since C# 6.0 you can declare:

    void WriteToConsole(string word) => Console.WriteLine(word)
    

    And then call it as usual:

    public static void Main()
    {
        var word = "Hello World!";
        WriteToConsole(word);
    }