Difference between => constant to { get; } = const

2019-01-27 12:10发布

问题:

This question already has an answer here:

  • Difference in C# between different getter styles 3 answers

In the context of best practice and performance (if any) what is better for exposing a value that is either set or calculated once as a property in C# 6+ style properties?

I'm comparing expression bodied properties

public string Name => "bob";

and auto-property initialisation

public string Name { get; } = "bob";

Does it desugar to the same thing? I can't find anywhere in the docs that says which to use for my case. I apologise if this is covered already in SO, the search got me no where.

回答1:

Beware! expression bodied properties will execute the expression every time they are called! You can see the examples in the last part of my answer.

public string Name => "bob";

Is syntactic sugar for

public string Name
{
    get
    {
        return "bob";
    }
}

While

public string Name { get; } = "bob";

is syntactic sugar for

private readonly string _name = "bob";

public string Name
{
    get
    {
        return _name ;
    }
}

Check it out yourself.

Beware - here is the dangerous part!

Please note that the expression body will be executed every time you call this property. That's fine when it's returning a hard coded value, but if it's returning a list, for example, it will return a new list every time:

public List<String> Names => new List<String>() {"bob"};

Is syntactic sugar for:

public List<string> Names
{
    get
    {
        return new List<string>() {"bob"};
    }
}

That is not the case with auto-property initialization:

public List<String> Names { get; } = new List<String>() {"bob"};

Is syntactic sugar for this:

private readonly List<string> _names = new List<string>() {"bob"};

public string Names 
{
    get
    {
         return _names;
    }
}

As you can see, here the list is only initialized once.

Check it out yourself.



回答2:

The first one is an arrow-function and results into a function which returns a constant value:

// syntactic sugar for:
public string Name { get { return "bob"; } }

// results into:
public string get_Name() 
{
    return "bob";
}

The second one is an auto-property, which results into a getter with backing field with value "bob":

// results into:
private string _name = "bob";
public string get_Name()
{
    return _name;
}


标签: c# c#-6.0