user4090029
user4090029

Reputation:

Cast to base class from derived class

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!

Upvotes: 1

Views: 123

Answers (1)

Dagon313
Dagon313

Reputation: 36

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.

Upvotes: 1

Related Questions