Setting readonly variables

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;
}
 
G

Guest

That's just it the compiler won't let me do this. I was wondering if there
is a way around the limitation?
 
G

Guest

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

Mattias Sjögren

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
 
G

Guest

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.
 

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

Top