tags:

views:

59

answers:

2

I have two constructors which feed values to readonly fields.

    class Sample
{
    public Sample(string theIntAsString)
    {
        int i = int.Parse(theIntAsString);

        _intField = i;
    }

    public Sample(int theInt)
    {
        _intField = theInt;
    }


    public int IntProperty
    {
        get { return _intField; }
    }
    private readonly int _intField;

}

One constructor receives the values directly, the other does some calculation and obtains the values, then sets the fields.

Now here's the catch:

  1. I don't want to duplicate the setting code. In this case, just one field is set but of course there may well be more than one.
  2. To make the fields readonly, I need to set them from the constructor, so I can't "extract" the shared code to a utility function.
  3. I don't know how to call one constructor from another.

Any ideas?

+10  A: 

Like this:

public Sample(string str) : this(int.Parse(str)) {
}
SLaks
This is nice, especially if you get it.
blizpasta
Nice solution!!
Jader Dias
I get it, and I like it. The sample, however, was of course simplified. I wonder if I can put my complicated method in the "this". I'll try it. Thanks.
Avi
@Avi: You can make a `static` method that manipulates the parameters.
SLaks
+1  A: 

before the body of the constructor, use either:

: base (parameters)

: this (parameters)

Example :-

public class People: User
{
   public People (int EmpID) : base (EmpID)
   {
      //Add more statements here.
   }
}
Sudantha