views:

52

answers:

2

Hi,

Is there any way to delay calling a superclass constructor so you can manipulate the variables first?

Eg.

public class ParentClass
{
   private int someVar;

   public ParentClass(int someVar)
   {
       this.someVar = someVar;
   }
}

public class ChildClass : ParentClass
{
    public ChildClass(int someVar) : base(someVar)
    {
        someVar = someVar + 1
    }
}

I want to be able to send the new value for someVar (someVar + 1) to the base class constructor rather than the one passed in to the ChildClass constructor. Is there any way to do this?

Thanks,
Matt

+4  A: 
public class ChildClass : ParentClass
{
    public ChildClass(int someVar) : base(someVar + 1)
    {
    }
}

Now if this manipulation is more complicated than incrementing an integer and deserves a separate method, you could call this method inside base but this method needs to be static.

Darin Dimitrov
yup. as a side note, i have seen some crazy stuff going on in a base ctor.
Sky Sanders
It is much more complicated... involves posting to a url, returning the html, traversing the dom, and grabbing a string. I can't make this method static and call it from the base because each subclass has a different implementation of grabbing the string and the base class has no way of telling which one to call.I could create an initialize method that sets all the variables for the base class... but that's leaving a setter for all the variables.
Matt
I doubt placing what you've just described in a constructor is a good idea. Just do the job, calculate whatever and once you are done pass the value to the constructor, put this logic elsewhere.
Darin Dimitrov
I guess that could work...
Matt
@Matt: This sounds more, that every ChildClass shouldn't derive from BaseClass. Moreover it should have one (maybe as private field). The drawback is that you have to implement all public properties and functions of the base in your child and forward each call manually. For this job interfaces can help (a little).
Oliver
A: 

How about the something like this? You can have different implementations ISomething and pass the required to the base class.

public interface ISomething
{
    int DoSomething(int someVar);
}

public class Something : ISomething
{
    private int someVar;

    public Something(int someVar)
    {
        this.someVar = someVar;
    }

    public int DoSomething(int someVar)
    {
        return someVar + 1;
    }
}

public class ParentClass
{
   private int someVar;

   public ParentClass(ISomething something)
   {
       this.someVar = something.DoSomething(someVar);
   }
}

public class ChildClass : ParentClass
{
    public ChildClass(int someVar) : base(new Something(someVar))
    {

    }
}
ravi