Question

I have this property

    /// <summary>
    /// The production date of the device is contained in its serial number.
    /// </summary>
    public DateTime Date
    {
        get 
        {
            return SerialNumber.Date;
        }
    }

However, I would expect I could write it like this

    /// <summary>
    /// The production date of the device is contained in its serial number.
    /// </summary>
    public DateTime Date
    {
        get return SerialNumber.Date;
    }

But I receive the error { or ; expected.

Now my question is: Why do I need braces here, while I do not wish to mark the beginning and end of a scope, as there is only one line of code.

It doesn't really matter that I do need to use braces. But in my opinion its not consistent with the rest of the interpretation of C# code.

You can use if(DoNotUseBraces) return null; for example, no braces necessary. Or even

if (SomeBoolean)
    return null;

Again, no braces necessary. I guess its the same as: Why do methods with only one statement need braces? but get does not implement the () like get() e.g.

Was it helpful?

Solution

Those brackets are not for a scope block, it's part of the syntax. The setter and getter are actually methods, so it's similar to the syntax for a function.

For an if statement the brackets are not part of the syntax:

if (<condition>) <statement>

For a property getter, the brackets is part of the syntax:

<type> <identifier> { get { <statements> } }

just as they are for a function:

<type> <identifier>(<parameters>) { <statements> }

OTHER TIPS

Because a property in C# can also have a setter:

public DateTime Date
{
    get return SerialNumber.Date;
    set SerialNumber.Date = value;
}

That would not work. Where does the getter end and where does the setter begin?

These scopes are clear even if you'd add multiple lines:

public DateTime Date
{
    get { return SerialNumber.Date; }
    set { SerialNumber.Date = value; }
}

Now my question is: Why do I need braces here, while I do not wish to mark the beginning and end of a scope, as there is only one line of code.

I assume that it was just too much work for the C# compiler team to implement something that is just a nice-to-have for a one liner property.

It's just a language design, is considered in that way. It's like concerning about fact that Lamborghini car has doors that opens to up and not to side like other cars. It's all about language design.

For complete Jon Skeet answer on this question, pointing to exact location of language specification that describes this, can have a look on:

Why this compile error

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top