Apologies for the vague nature of the question. I couldn't think of a concise way to explain the problem I seem to be facing for the Nth time and which I think must be an extremely common scenario. Code explains it best...
abstract class LogicBase {}
class LogicSubclassA : LogicBase{}
class LogicSubclassB : LogicBase{}
abstract class GraphicsBase
{
public GraphicsBase( LogicBase logicObject ) => LogicObject = logicObject;
public LogicBase LogicObject { get; private set; }
}
class GraphicsSubclassA : GraphicsBase
{
public GraphicsSubclassA( LogicBase logicObject ) : base( logicObject ) {}
}
class GraphicsSubclassB : GraphicsBase
{
public GraphicsSubclassB( LogicBase logicObject ) : base( logicObject ) {}
}
All okay so far. Now the problem is that in a concrete graphics object (e.g.
GraphicsSubclassB
) code sometimes needs to refer to its specific associated logic object (
LogicSubclassB
). Since I know what the type of the logic object is supposed to be, I can use a straightforward cast or the
as
operator. So I could simply have this:
class GraphicsSubclassB : GraphicsBase
{
public GraphicsSubclassB( LogicBase logicObject ) : base( logicObject ) {};
public LogicSubclassB StronglyTypedLogicObject => (LogicSubclassB)LogicBase;
}
But is there a way to express this in
GraphicsBase
? Is there a way to express that each subclass of
GraphicsBase
must provide its own implementation of the
StronglyTypedLogicObject
property?
What I have tried:
The only way I can think this might work is using generics, something like the following (which
does not compile)...
abstract class GraphicsBase<T> where T : LogicBase
{
public GraphicsBase( LogicBase logicObject ) => LogicObject = logicObject;
public LogicBase LogicObject { get; private set; }
public virtual T StronglyTypedLogicObject => LogicObject;
}
class GraphicsSubclassB<T> : GraphicsBase<LogicSubclassB>
{
public GraphicsSubclassB( LogicBase logicObject ) : base( logicObject ) {}
public override T StronglyTypedLogicObject => (T)LogicObject;
}