1

My code:

class MyBaseClass 
{ 
    public void Print() 
    { 
        Console.WriteLine("This is the base class."); 
    } 
} 

class MyDerivedClass : MyBaseClass 
{ 
    new public void Print() 
    { 
        Console.WriteLine("This is the derived class."); 
    } 
} 

class Program 
{ 
    static void Main() 
    { 
        MyDerivedClass derived = new MyDerivedClass(); 
        MyBaseClass mybc = (MyBaseClass)derived; 

        derived.Print(); // Call Print from derived portion. 
        mybc.Print(); // Call Print from base portion. 
    } 
} 

If I change the line: MyBaseClass mybc = (MyBaseClass)derived; to MyBaseClass mybc = new MyBaseClass();, the result was the same to.

My question: Can you tell me what is the difference?

Thanks!

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
  • 2
    this is another of the `new` vs. `override` questions - if you want a different behaviour you have to make `Print` virtual and use `overloads` instead of `new` – Random Dev Oct 15 '14 at 05:16
  • override, not overload – Jonas Høgh Oct 15 '14 at 05:19
  • possible duplicate of [C# keyword usage virtual+override vs. new](http://stackoverflow.com/questions/159978/c-sharp-keyword-usage-virtualoverride-vs-new) – Random Dev Oct 15 '14 at 05:20

1 Answers1

1

Well, your first code was a cast. Meaning any attributes you inherited would still be in your object mybc after that cast.

While

MyBaseClass mybc = new MyBaseClass();

is simply creating a completetely new instance of your base class. Since you hard coded your print method, it cannot change any output, since they're both of the same type.

If you would print an attribute of your class, like a name and a number, you would see the difference.

Dagon313
  • 46
  • 4