简体   繁体   中英

The difference between type casting and a polymorphic function call?

I'm reading Rihter's book on c# and I am wondering how type casting works.

Say I have this code:

    class Parent
    {
        public virtual void DoStuff()
        {
            //... some code
        }
    }

    class Child : Parent
    {
        public override void DoStuff()
        {
            // .. some different code
        }
    }

Now in the Main() function I call this:

        Parent child = new Child();
        child.DoStuff();

How is this different from type casting? According to Rihter the CLR will follow the child's link to the child's type-object (Child) in memory and retrieve the pointer to the Child.DoStuff() version of the method. To me that sounds like the same operation as this:

        ((Child)child).DoStuff();

Where am I wrong?

How is this different from type casting?

Polymorphism is very different than type casting and a key foundation of OO programming languages. Your example doesn't really showcase anything about the usefulness of the feature.

Consider the following example:

 abstract class Animal {
     public abstract string MakeSound(); }

 void PrintSound(Animal animal) { Console.WriteLine(animal?.MakeSound(); }

And now the typical scenario of a callsite with an argument only known at runtime:

var animal = makeUserChooseAnimal(); //no idea what animal this will be
PrintSound(animal);

Where exactly would you fit in the cast you are asking about? But polymorphism and the virtual call will make it possible, that no matter what animal is really passed into PrintSound , the appropiate MakeSound() will be called.

Now, if what you are interested in is understanding how the CLR figures out what method to call, then I'd recommend you read Eric Lippert's three part series on the subject, starting here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM