Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# virtual methods question

There is a thing I do not understand well: when virtual method is called, the base method is called as well?

Because when I use public override WinForm OnPaint method, in its body base.OnPaint(e) is called. I do not understand it, I thought virtual methods overrides the original one. If it is not usually called, why it is called in this case? Thank you

like image 718
Snake Avatar asked Jan 20 '26 14:01

Snake


2 Answers

No, it is not called, if you don't call it explicitly from the derived class.

like image 110
onof Avatar answered Jan 22 '26 04:01

onof


when virtual method is called, the base method is called as well?

No.

Because when I use public override OnPaint(), in its body base.OnPaint(e) is called. I do not understand it, I thought virtual methods overrides the original one.

The developer chose to call base.OnPaint(e) and also do something else. In other words, the base implementation is something which you have at your hand in case it is useful to you - you can call it, and then do some additional specific work.

If the function body was only a call to the base, then it would be equivalent to not writing the overriding function at all.

like image 20
Daniel Daranas Avatar answered Jan 22 '26 05:01

Daniel Daranas