I'm trying to enforce an inheritor of an abstract class to initialize one of the fields in the base.
I can't do this via a constructor in the base because the type of the field requires a reference back to the object creating it. (I suppose I could provide a parameterless ctor for the field type. But I feel that would just be shifting the problem, and it should be immutable anyway).
Perhaps someone can suggest how to do it, or maybe make it so I don't need to do it at all?
This is pretty much what I'm doing:
public abstract class Base
{
// Would like to force setting in CTOR
protected BaseImplementation _implementation;
protected BaseImplementation Implementation
{ get { return _implementation; } }
public void DoSomething()
{
Implementation.DoSomething();
}
}
public abstract class BaseImplementation
{
public abstract void DoSomething();
}
public class MyObject : Base
{
// Note its Nested
public class MyImplementation : BaseImplementation
{
private MyObject _myObject;
public MyImplementation(MyObject myObject)
{
this._myObject = myObject;
}
public override void DoSomething()
{
// Does something
}
public virtual void SomethingElse()
{
// Does something else
}
}
new public MyImplementation Implementation
{
get { return (MyImplementation) _implementation; }
}
public void SomethingElse()
{
Implementation.SomethingElse();
}
}
To give a little context, I have a number of classes which inherit from the base. They, intern have multiple ways which they can manipulate their state. This has been the best solution I have come up with for handling that.
Edit
I forgot to mention that I'm not using an Abstract property because it means I cant use new public MyImplementation Implementation {...
. I don't want to have to cast Implementation to MyImplementation whenever I use functionality specific to the derived class (thus using new
in the first place) or create multiple fields containing the same object.