Navaneeth

Hello,

I have two classes say BaseClass and ChildClass. Second one is derived from first. I am creating object like

Code Block

BaseClass obj = new ChildClass();



This works correctly. But when we need such a instantiation And what is the benefit of doing so Any help will be appreaciated.



Re: Visual C# General Initializing base class with a child class instance

Alberto Poblacion

Assigning a child class to a base class is useful when you are going to use polymorphism. Imagine that BaseClass has a virtual method "TheMethod", which is overidden in ChildClass. if you were to invoke obj.TheMethod, you would execute the method in ChildClass instead of the one in BaseClass.

This is frequently used when you write a flexible method that is designed to work with a base class. For instance, tha class XmlDocument in the .Net framework has a method Save(Stream s). You can create a MemoryStream (which is a child of Stream) and pass it to the Save method. When Save calls the Write method on the Stream, it executes the Write in MemoryStream, thus saving the XmlDocument to its intended destination, without any need for the developers of the XmlDocument class to know anything about MemoryStreams or other child classes of Stream.





Re: Visual C# General Initializing base class with a child class instance

Navaneeth

Thanks. It helped