Sometimes I see classes defined with readonly members like so:
class Foo
{
private readonly string bar;
public Foo(string bar)
{
this.bar = bar;
}
public string Bar => bar;
}
and other times I see classes defined with readonly members like so:
class Foo
{
public Foo(string bar)
{
Bar = bar;
}
public string Bar { get; private set; }
}
The second example looks a lot more readable/succinct to me, but I was wondering if there is any legitimate reason for explicitly defining a readonly
backing field (as per the first example) ?
Qudos for an in-depth analysis of the two examples, ideally covering what's really going on under the hood, in the CLR.
Definition and UsageA read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text from it). The readonly attribute can be set to keep a user from changing the value until some other conditions have been met (like selecting a checkbox, etc.).
A class property declared read-only is only allowed to be initialized once, and further changes to the property is not allowed. Read-only class properties are declared with the readonly keyword* in a typed property.
Use the readonly keyword when you are not sure whether the value of a variable of an object needs to change but you want to prevent other classes from changing the value. Use the static keyword when you want the member of a class to belong to the type rather than to the instance of the type.
A readonly field can be assigned and reassigned multiple times within the field declaration and constructor. A readonly field can't be assigned after the constructor exits.
The first is a short way of writing
class Foo
{
private readonly string bar;
public Foo(string bar)
{
this.bar = bar;
}
public string get_Bar() { return this.bar; }
}
That's all a property with a getter is; it's just a short way of writing a getter function.
The second is a short way of writing
class Foo
{
private string __bar;
public Foo(string bar)
{
this.set_Bar(bar);
}
public string get_Bar() { return this.__bar; }
private void set_Bar(string b) { this.__bar = b; }
}
Where again, a property is just a pair of get/set methods behind the scenes.
I was wondering if there is any legitimate reason for explicitly defining a readonly backing field
Either form is perfectly legitimate. Pick the one you like better.
I note that the two forms are not equivalent. In the first case the property's backing field can only be changed in the constructor; in the latter, the property's backing field can be changed anywhere in the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With