I’ve created a derived class with its own derived settings.
public abstract class BaseClass
{
public BaseClass(Game1 game, BaseClassSettings settings)
{
if (settings == null)
{
Console.WriteLine("BASE PANIC!");
}
}
public abstract BaseClassSettings Write();
}
public abstract class BaseClassSettings
{
public abstract BaseClass Load(Game1 game, BaseClassSettings settings);
}
When instantiating the class I overload the constructor to call the base class and create a new instance of the correct derived settings.
public class DerivedFoo : BaseClass
{
public DerivedFoo(Game1 game, DerivedFooSettings settings)
:base(game, settings == null ? new DerivedFooSettings() : settings)
{
if (settings == null)
{
Console.WriteLine("DERIVED PANIC!");
}
}
public override BaseClassSettings Write()
{
DerivedFooSettings settings = new DerivedFooSettings();
return settings;
}
}
public class DerivedFooSettings : BaseClassSettings
{
public override BaseClass Load(Game1 game, BaseClassSettings settings)
{
return new DerivedFoo(game, settings as DerivedFooSettings);
}
}
The problem with this method is that the tertiary operator only works for the base class and doesn’t pass a new instance into the derived class constructor. (‘settings’ remain null)
How can I automatically pass the settings without having to duplicate the tertiary operator in the constructor method for the derived class?
I can’t store the settings in the base class as they will not be of the correct type.
It’s ugly, but you could change the
basecall to assign the value you’re passing back tosettings:Note that this isn’t doesn’t change what’s passed to the
DerivedFooconstructor – it just changes the value of thesettingsparameter within the constructor.Of course if
BaseClassexposed aSettingsproperty – possibly protected – and set that during the constructor, you could just use the property value within theDerivedFooconstructor body. That would be cleaner, IMO – I don’t think I’ve ever used an assignment expression within a constructor chain call like this…