Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly getters VS property-like functions

Tags:

c#

c#-6.0

With C#6 came some new features, including getter-only auto-properties and property-like function members.

I'm wondering what are the differences between these two properties? Is there any reason why I'd prefer one to another?

public class Foo
{
    public string Bar {get;} = "Bar";
    public string Bar2 => "Bar2";
}

I know that {get;} = can only be set by a static call or a constant value and that => can use instance members. But in my particular case, which one should I prefer and why?

like image 443
IEatBagels Avatar asked Dec 01 '15 20:12

IEatBagels


People also ask

Can properties be private in c#?

Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property.

Can readonly property be set in constructor?

You can initialize a ReadOnly property in the constructor or during object construction, but not after the object is constructed.

What is private readonly in C#?

The readonly keyword is a modifier that can be used in four contexts: In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class.

What is get and set c#?

The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.


1 Answers

It's easiest to show them in terms of C# 1:

public class Foo
{
    private readonly string bar = "Bar";
    public string Bar { get { return bar; } }

    public string Bar2 { get { return "Bar2"; } }
}

As you can see, the first involves a field, the second doesn't. So you'd typically use the first with something where each object could have a different state, e.g. set in the constructor, but the second with something which is constant across all objects of this type, so doesn't need any per-object state (or where you're just delegating to other members, of course).

Basically, ask yourself which of the above pieces of code you would be writing if you didn't have C# 6 available, and choose the corresponding C# 6 path.

like image 78
Jon Skeet Avatar answered Oct 01 '22 23:10

Jon Skeet