Setting readonly variables

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I've applied readonly variables to my code where its seemed useful to do so,
such as
readonly string m_name;

public MyClass(string name)
{ m_name = name); }

Where I have had multiple constructors for a class I have had to apply all
the settings to one constructor or set each variable in different
constructors:

public MyClass(string name) : this(name, "")
{ }
public MyClass(string name, string address)
{ m_name = name;
m_address = address; }

However is it possible to set multiple constructors through a method in the
class called by the constructor? Something like:

public MyClass(string name) : this(name, "")
{ }
public MyClass(string name, string address)
{ Initalize(); }
private void Initialize()
{
m_name = name;
m_address = address;
}
 
That's just it the compiler won't let me do this. I was wondering if there
is a way around the limitation?
 
However is it possible to set multiple constructors through a method in the
class called by the constructor?

readonly fields can only be set inline (i.e on the line where they are
declared) or inside a constructor, so I think you are stuck putting them in
one constructor that the other constructors call.
 
That's just it the compiler won't let me do this. I was wondering if there
is a way around the limitation?

Seems you already know the workaround; call another constructor using
this(...). Why do you want to move the code to an Initialize method
instead of having it in a constructor?



Mattias
 
Sometimes it can seem like more work to have to ensure that all the variables
are handled correctly, have right default values when passing into
this(?,?,etc)

Also it seems more sensible to put routines that are used by more than one
place into a single method. However I see this is not allowed with C# OO
design.
 
Back
Top