You can do this but not with automatic properties, you should just create
your own backing store and make it a readonly (just a get) properties which
returns a readonly variable.
Typos aside, yes - it would be very nice to be able to declare
readonly auto-implemented properties, especially for writing immutable
classes. Presumably it would have to be a "private readonly" to make
sense. However, this simply isn't in the language at the moment.
You have two choices: for a true immutable, do it the long way:
private readonly string name;
public string Name {get {return name;}}
(and assign this.name in the ctor)
For a semi-immutable object, make the set private and simply don't set
it after the ctor:
public string Name {get; private set;}
(and assign this.Name in the ctor)
In my opinion its still nice for encapsulation to have this as a property, to
shield the outside world from the source of the data. It could be possible in
future to change this to make Name = firstname + " " + lastname; and the
property would hide this from consumers.
In my opinion its still nice for encapsulation to have this as a property,
to
shield the outside world from the source of the data. It could be possible
in
future to change this to make Name = firstname + " " + lastname; and the
property would hide this from consumers.
At which point I would change it from a field to a property. I always use
fields for readonly because it saves typing, unless I need to use the class
as a datasource and therefore it must be a property, but then I usually need
a setter that does nothing just to get a column to show anyway.
The only issue with changing it when the needs change is that you would need
to rebuild the consumers even though you wont need to change their code.
Having it as a property from the start means you could just deploy a new
version of the assembly containing this code.
In my opinion its still nice for encapsulation to have this as a property,
to
shield the outside world from the source of the data. It could be possible
in
future to change this to make Name = firstname + " " + lastname; and the
property would hide this from consumers.
>
At which point I would change it from a field to a property. I always use
fields for readonly because it saves typing, unless I need to use the class
as a datasource and therefore it must be a property, but then I usually need
a setter that does nothing just to get a column to show anyway.
>
>
Pete
>
>
Comment