Reputation: 8746
Suppose you have the following class declarations:
public abstract class Foo
{
public class Bar
{
public virtual void DoSomething() { ... }
}
}
Is it possible to override Bar.DoSomething() in a child class of Foo, a la:
public class Quz : Foo
{
public override void Bar::DoSomething() { ... }
}
Obviously that syntax doesn't work, but is something like this possible?
Upvotes: 2
Views: 555
Reputation: 32515
No, but you can still inherit from the Foo.Bar
class itself:
public class BarDerived : Foo.Bar
{
public override void DoSomething() { ... }
}
I feel I should explain that doing this will not mean that a class deriving from Foo
will all of a sudden have an inner class of BarDerived
instead, it just means that there is a class that can be derived from it. There are ways of replacing what type of class you want to use as the inner class, for example:
public class Foo<T>
where T : Foo.Bar
{
private T _bar = new T();
public class Bar
{
public virtual void DoSomething() { ... }
}
}
public class BarDerived : Foo.Bar
{
public override void DoSomething() { ... }
}
public class Quz : Foo<BarDerived> { ... }
Upvotes: 6
Reputation: 3443
Well, if you are following good practices, then the Bar
cannot be constructed by any other class then Foo
, that said enables the following:
Create a derived class from Foo::Bar
in Quz
, and override it's DoSomething()
override each method in Foo
where Bar
is constructed and provide the derived class instead.
the user of Foo
should not know the difference in API between Bar
and your new derived inner class.
hope this makes sense.
Upvotes: 0
Reputation: 101701
No, only if you inherit from Bar
public class Quz : Foo.Bar
{
public override void DoSomething() { ... }
}
Upvotes: 1