Search code examples
c#inheritanceconstructor

c# child constructor calls parent constructor depending on a value


This is my problem, I have it sorted, but I think that there is a better way of doing this:

I have the following code:

public class A
{
    public A(int paramA, int paramB)
    {
       ParamA = paramA;
       ParamB = paramB;
    }

    public int ParamA { get; set; }
    public int ParamB { get; set; }
}

I also have the following code:

public class B : A
{
    public B(int c, int d, int paramA, int paramB)
    {
        C = c;
        D = d;
        if (C == 0)
        {
            ParamA = paramA - D;
            ParamB = paramB;
        }
        else
        {
            ParamA = paramA;
            ParamB = paramB;
        }
    }

    public int C { get; set; }
    public int D { get; set; }
}

In other words, the value assigned to ParamA depends on the value of C. I know that you can do something like public B(int c, int d, int paramA, int paramB) : base(paramA, paramB), but that's not what I want, as paramA will be assigned to ParamA whatever C is. The code works, but is there other better way of doing it?

Edit: responses to the comments:

Yes, it has a parameterless constructor that is not in the code. Yes, properties are mutable, that is on purpose, there is more code. At this stage, I am trying to achieve a clean code, just that in child class parent parameters depend on some specific values in child parameters.


Solution

  • Obviously I don't know your exact reasons for doing so, but I'd be inclined to try and have just a single Mortgage class with the overpayment logic on it and maybe use a flag to identify there is an overpayment.

    That aside, you could do something like the following:

    public class A
    {
        public A(int paramA, int paramB)
        {
            ParamA = paramA;
            ParamB = paramB;
        }
    
        public int ParamA { get; set; }
    
        public int ParamB { get; set; }
    }
    
    public class B : A
    {
        public B(int c, int d, int paramA, int paramB) 
            : base(paramA, paramB)
        {
            C = c;
            D = d;
            
            if (C == 0)
            {
                ParamA -= D;
            }
        }
    
        public int C { get; set; }
    
        public int D { get; set; }
    }
    

    You could also check if C == 0 in the base call but I don't advise it (less readable for a start in my opinion).

    public class B : A
    {
        public B(int c, int d, int paramA, int paramB) 
            : base(c == 0 ? paramA - d : paramA , paramB)
        {
            C = c;
            D = d;
        }
    
        public int C { get; set; }
    
        public int D { get; set; }
    }