Reputation: 827
Given the following code:
interface IParent
{
void ParentPrintMethod();
}
interface IChild : IParent
{
void ChildPrintMethod();
}
class Baby : IChild
{
public void ParentPrintMethod()
{
Console.WriteLine("Parent Print Method");
}
public void ChildPrintMethod()
{
Console.WriteLine("Child Print Method");
}
}
All is well at this point. If you were to create a new instance of the Baby class as follows,
Baby x = new Baby();
everything is ok, and you would have access to the ParentPrintMethod() and the ChildPrintMethod();
However, can somebody please explain to me what would happen if you were to do the following?
IParent x = new Baby();
Would you have access to the ChildPrintMethod() in this case? What exactly is happening when you do this?
Upvotes: 0
Views: 102
Reputation: 13907
This sounds really abnormal but: All Child
ren are Parent
s, but not all Parent
s are Child
ren.
It doesn't make sense for a Parent
to access a Child
s methods because it would be an error in the case that the parent isn't a child.
It is still possible to access the child methods in your example given, but you must cast x
to a Child
first, ((Child)x).ChildPrintMethod()
. This is sound because in the event that x is not a valid Child, an exception is thrown when the cast happens, rather than attempting to run the method.
You can test ahead whether this should work, rather than having to catch exceptions by using if (x is Child)
Edit:
To reuse the variable as if it were a child, you can create a local reference to it like this:
if (x is Child) {
Child y = (Child)x;
...
}
Upvotes: 2
Reputation: 27974
There is no such thing as "inheritance skipped". Your object is just viewed 'through' one of its interfaces, effectively hiding anything else not declared in that interface. There's no magic in it.
Upvotes: 1
Reputation: 40789
Your reference to the object will behave like an instance of the Parent interface and will not have access to the Child methods.
Upvotes: 2
Reputation: 20157
No, you would not. The variable x
, as type Parent
(by the by, interfaces are idiomatically named with an I
at the beginning) would only see the methods defined in the Parent
interface. Period.
Upvotes: 3
Reputation: 4339
Then you're specifying you're interested only in the Interface
declared by Parent
so you would only have access to those methods declared in Parent
even if the instance of the object itself has more available.
Upvotes: 3