Cyberherbalist
Cyberherbalist

Reputation: 12309

What practical difference is there between properties defined with expressions and the traditional way?

I retired from full-time programming in .NET C# in 2016, but have just recently come back as a hobbyist programmer. I was interested to discover a new way to code properties, using fat arrows:

public DateTime PicDate { get => _picDate; set => _picDate = value; }

This is what I was used to (as well as the get; set; thing):

public int Century
{
    get
    {
        return _century;
    }
    set
    {
        _century = value;
    }
}

Aside from ease of coding, is there any real practical difference in implementation? Does C# 7 handle the new way more efficiently than the old way?

In other words, is the new syntax "better" than the old?

Upvotes: 2

Views: 68

Answers (1)

Mafii
Mafii

Reputation: 7435

It is exactly the same. It compiles to the same underlying IL code.

However, I would recommend using auto-properties, so you don't have to handle backing fields yourself:

public DateTime PicDate { get; set; }

Is exactly the same as

private DateTime _picDate;

public DateTime PicDate 
{ 
  get { return _picDate; }
  set { _picDate = value; }
}

And that is the exact same as your example with the => syntax (as Dave said: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members).

Hope this clears things up!

Upvotes: 5

Related Questions