Geeks With Blogs
finally{} My interactions with .Net and Web development - What's most important is what happens finally{}

/* 1) Base obj = new Derived();
 * Untill and unless you've a method overridden
 * in the derived class, whether or not you say "new method"
 * in the derived class, the base class's
 * method would get called.
 */
Salary objBaseDerSalary = new DerivedSalary() ;
MessageBox.Show("objBaseDerSalary.myMethod() " + objBaseDerSalary.myMethod());

/* 2) Derived obj = new Base();
 * Gives compilation error, because the parent
 * cannot be implicitely converted to the derived.
 * DerivedSalary objBaseDerSalary1 = new Salary();
 * MessageBox.Show("objBaseDerSalary.myMethod() " + objBaseDerSalary1.myMethod());
 */

/* 3) Derived obj = (Derived) new Base();
 * Gives Runtime error "specified cast isn't valid"
 * You cannot downcast a base class.
 * DerivedSalary objTCBaseDerSalary = (DerivedSalary) new Salary();
 * MessageBox.Show("objTCBaseDerSalary.myMethod() " + objTCBaseDerSalary.myMethod());
 */

/*  4) Derived obj = new Derived();
 *  obj.myMethod(); will always call the derived
 *  myMethod whether or not you say "new method"
 *  in the derived class.
 */
 DerivedSalary objDerDerSalary = new DerivedSalary();
 MessageBox.Show("objDerSalary.myMethod() " + objDerDerSalary.myMethod());

/* Conclusion:
 * Its the declared object's method that will get called.
 * Unless you override, the base class's method will get called,
 * if you've declared the object to be of base class.
 */

Posted on Friday, August 19, 2005 7:55 AM .Net Framework , C# | Back to top


Comments on this post: Base class and Derived class relationship in C#.Net

# re: Base class and Derived class relationship in C#.Net
Requesting Gravatar...
A little clearer format then you may get more comments, too difficult to read english text in C# format.

Good try
Left by Moe on Oct 09, 2008 3:01 PM

Your comment:
 (will show your gravatar)


Copyright © Vinayak | Powered by: GeeksWithBlogs.net