Reputation: 447
I'm a little new to C# and I've achieved something where I'm confused why this has been allowed.
public interface IBase
{
}
public interface ISub : IBase
{
}
public class Thing
{
protected IBase provider;
public Thing(IBase provider)
{
this.provider = provider;
}
}
public class AnotherThing : Thing
{
protected ISub provider;
public AnotherThing(ISub provider) : base(provider)
{
this.provider = provider;
}
}
I hope I'm just being dense, but I don't understand how I am allowed to override provider
without causing some confusion to the compiler.
The code does work.
Upvotes: 1
Views: 1225
Reputation: 82136
You should get a warning indicating that provider
in AnotherThing
is hiding an inherited member.
Effectively what happens is the compiler ignores provider
in Thing
when in the context of AnotherThing
- it's known as name hiding.
Upvotes: 0
Reputation: 62296
You ask about second case I presume: you don't override anything, you just declare a new protected variable and explicitly reference it with this
:
this.provider = provider;
As provider parameter is of type ISub
the same type as the this.provider
, compiler knows what variable you mean exactly.
Upvotes: 1
Reputation: 55750
I'm surprised you are not getting any warning either.
What you are doing is hiding the protected member provider
by providing a new declaration for it in the derived class. This is allowed, but you should decorate the declaration with the new keyword to make it more explicit that you intended to hide the member and it was not just an accident/oversight.
Upvotes: 3