Properties intitialized in ctor

  • Thread starter Thread starter puzzlecracker
  • Start date Start date
P

puzzlecracker

Why cannot properties be initialized in a constructor, especially read-
only onces.

public class {

pubic string Name {get, readonly set;}

}
 
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)

Marc
 
If it is readonly then it is a field and not a property....

public class Person
{
public readonly string Name;
}


Pete
 
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.


Pete
 
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top