public class Parent
{
public virtual Parent me()
{
return this;
}
}
public class Child : Parent
{
}
new Child().me() is returning a Parent object. What do i need to have it return the Child object itself (without using extension and generic)??
The
memethod is returning a reference to the actual object, which is of the typeChild, but the type of the reference is of the typeParent.So, what you have is a reference of the type
Parentthat points to an object of the typeChild. You can use that to access any members that theChildclass inherits from theParentclass. To access the members of theChildclass you have to cast the reference to the typeChild:You could make the
memethod return aChildreference and do the casting inside the method, but then it will of course not work to return a reference to aParentobject. If you don’t use generics, each method can only have one return type. Even if you override the method in theChildclass, it still has to return the same data type as in theParentclass.