When you do
BaseClass baseObject= new ChildClass();
The static declared type of the object is that of "BaseClass
".
Hence you can only see the objects of "BaseClass"
type.
If you are sure that the object is of ChildClass Type, you can typecast baseObject to "ChildClass" and then use the ChildClass members
((ChildClass) baseObject).
- should help intellisense give you the members of the child class.
Using BaseClass baseObject= new ChildClass();
is the base for RunTime polymorphism.
It is very commonly used if you need the overridden child logic to be called but the interface is that of the base class
EDIT : Example of a scenario where you would use it
Class User
has derived classes called Employee
and 3rdPartyUser
Class User has a virtual method called GetRoleInformation - which is used to obtain Role Info for user from the companies Active directory.
However, for 3rd party user, as the information does not exist in AD, the logic for getting the Role Information involves calling a Web Service to retrieve the data.
In this case, GetRoleInformation is overridden in 3rdPartyUser class
Now, in the program, on the Login Page, once authenticated, i either get back an object of Employee or 3rdPartyUser.
I pass this object to a method with a signature RoleCollection GetRole( User loggedInUser)
Inside this method, without having to determine the type of the user, i just call loggedInUser.GetRoleInformation
and depending on whether it is Employee / 3rdPartyUser
, the appropriate base / overridden method will be called and Role data will be retrieved from either AD / Web Service.
Long story short :
Advantage of
BaseClass baseObject= new ChildClass();
OVER
ChildClass baseObject= new ChildClass();
is in scenarios when you are not sure of the exact type of child object that is going to be assigned to baseObject variable eg: in this case Employee / 3rdPartyUser
Eg:
BaseClass baseObject= GetLoggedInUser();
where signature of this method is User GetLoggedInUser(string userid)
Otherwise, in an example like yours, where the object is ALWAYS of type "ChildClass", i beleive that there is no advantage to doing it.