Difference between shadowing and overriding in C#?

后端 未结 6 812
面向向阳花
面向向阳花 2020-11-22 07:25

What\'s difference between shadowing and overriding a method in C#?

6条回答
  •  孤独总比滥情好
    2020-11-22 07:32

    Basically if you have something like below,

    Class A
    {
    }
    
    Class B:A
    {
    }
    
    A a = new B();
    

    Any method you call on the object 'a' will be made on the type of 'a'(Here the type is 'A') But if you implement the same method in class B that is already present in Class A, the compiler will give you a warning to use a "New" keyword. If you use "New", the warning will disappear. Other than this there is no difference between using "New" or not using it in the inherited class.

    In some situations you may need to call a method of the reference class the particular instance holds at that moment instead of calling a method on the object type. In the above case the reference it holds is 'B', but the type is 'A'. So if you want the method call should happen on 'B', then you use Virtual and override to achieve this.

    Hope this helps...

    Daniel Sandeep.

提交回复
热议问题