Home > OS >  C# How to pass properties to base class with optional values?
C# How to pass properties to base class with optional values?

Time:01-18

In the code example below, if HighValue and LowValue properties are not set by the client, how can I pass default values for these properties to the base class?

If there is a design mistake in this example setup, I'd like to thank you in advance for warning me.


public class Foo
{
    public Foo(int scaleHigh, int scaleLow)
    {
        ScaleHigh = scaleHigh;
        ScaleLow = scaleLow;
    }

    public int ScaleHigh { get; }
    public int ScaleLow { get; }
}


public class Bar : Foo
{
    public Bar(Bar bar)
        : base(bar.ScaleHigh, bar.ScaleLow)
    {
        HighValue = SomeHelper.ReCalculate(bar.HighValue);
        LowValue = SomeHelper.ReCalculate(bar.LowValue);
    }

    public int HighValue { get; }
    public int LowValue { get; }
}


public class SomeHelper
{
    public static int ReCalculate(int scale)
    {
        return scale * 5;
    }
}


public class Client : Bar
{
    public Client(Bar bar) : base(bar) { }

    public int Request(bool condition)
    {
        return condition ? HighValue : LowValue;
    }
}

CodePudding user response:

you have a bug in your bar class, since it doesn't have a default constructor, you will never be able to create the object, since it will be a recursion forever - each new instance would neeed another and so on

public class Bar : Foo
{
    public Bar(Bar bar)
        : base(bar.ScaleHigh, bar.ScaleLow)
    {
        HighValue = SomeHelper.ReCalculate(bar.HighValue);
        LowValue = SomeHelper.ReCalculate(bar.LowValue);
    }

    public int HighValue { get; }
    public int LowValue { get; }
}

you can fix it by adding another constructor like this

public Bar(int scaleHigh=0, int scaleLow=0, int highValue=0, int lowValue=0)
        : base(scaleHigh, scaleLow)
    {
        HighValue = SomeHelper.ReCalculate(highValue);
        LowValue = SomeHelper.ReCalculate(lowValue);
    }

CodePudding user response:

Try this:

public int LowValue { get; } = 0; //You can change these values.
public int HighValue { get; } = 10;

CodePudding user response:

Sorry if I misunderstand, but I believe you want to set default values of Bar if they are not set? In what case would the constructor not set the values?

In the case that you didn't set those in your constructor, one thing you can consider is making the types int? and then set the variable like this:

public int? HighValue => HighValue ?? (defaultValue)

  •  Tags:  
  • Related