Reputation: 3
I need classes as shown below but I'm unable to override context in Child Class because signature is different
class BaseContext{}
class ChildContext:BaseContext{}
abstract class Base
{
abstract BaseContext context{get;}
...
}
class Child : Base
{
public override ChildContext context{get;}
...
}
Is there any better approach for this?
Upvotes: 0
Views: 402
Reputation: 36729
There is Covariant return types that should make your example work if you just fix the access modifiers to both be public or protected. But this feature is only available in .net 5 and later.
For older versions you can do add a new modifier to create a new property with the same name:
public class BaseContext{}
public class ChildContext : BaseContext{}
public abstract class Base
{
public BaseContext Context => ContextImpl;
protected abstract BaseContext ContextImpl { get; }
}
public class Child : Base
{
public new ChildContext Context { get; }
protected override BaseContext ContextImpl => Context;
}
This patter can be used to provide different levels of access depending on the reference type you have. The pattern is a bit easier to implement with interfaces since you can use Explicit interface implementation to achieve the same thing, no need for a hidden abstract property.
public interface IBase
{
BaseContext Context { get; }
}
public class Child : IBase
{
BaseContext IBase.Context => Context;
public ChildContext Context { get; }
}
Upvotes: 0
Reputation: 119186
I would consider using generics here. For example:
// Make the base class generic
public abstract class Base<TContext>
where TContext : BaseContext // constrain the generic type to be a BaseContext
{
public TContext context { get; }
}
public class Child : Base<ChildContext>
{
// And here we no longer have to override the property
}
Upvotes: 2