So I've created a framework for settings in my application, all been good until I came across this little roadbump.
In the abstract base class I have this:
public abstract class SettingsBase
{
public event SettingsChangedEventHandler SettingsChanged;
public void NotifyChange() { NotifyChange(this); }
private void NotifyChange(object sender, EventArgs args = null)
{
SettingsChanged?.Invoke(this);
}
protected void OnSetChildSettings(ref SettingsBase settings, SettingsBase value)
{
if (Equals(settings, value)) return;
if (settings != null) settings.SettingsChanged -= NotifyChange;
settings = value;
if (settings != null) settings.SettingsChanged += NotifyChange;
}
}
Which is a cut down version showing just the code that's causing me grief.
And this in one implementation:
public class ChildSettings : SettingsBase { }
And here is the where the compiler error shows up:
public class ParentSettings : SettingsBase
{
private ChildSettings _childSettings;
public ChildSettings ChildSettings
{
get { return _childSettings; }
set { OnSetChildSettings(ref _childSettings, value); }
}
}
It's driving me mad, saying: "The 'ref' parameter type doesn't match parameter type". It's definitely a SettingsBase, do I have do a cast? Do I have to do template with constraints? This is very poor of C# to not work if so, though maybe I am just spoiled after using it for a few years now.
Edit - This works:
protected void OnSetChildSettings<T>(ref T settings, T value) where T : SettingsBase
{
if (Equals(settings, value)) return;
if (settings != null) settings.SettingsChanged -= NotifyChange;
settings = value;
if (settings != null) settings.SettingsChanged += NotifyChange;
}
Although I have a working solution I still want to understand what was wrong and why, so answers are still greatly appreciated.
Edit2 - Fixed naming, I just changed it to simply things for this question and missed some. Thanks :)