Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the base Keyword be used?

Tags:

c#

.net

When calling methods on a base class from a derived class, should the 'base' keyword be used? It seems using the base keyword would increase code readability but for me so far, when I exclude it, there is no affect on code compilation and execution.

like image 999
DaveB Avatar asked Nov 29 '22 05:11

DaveB


2 Answers

The base keyword is important when overriding methods:

override void Foo()
{
  base.Foo();
  // other stuff
}

I never use it for anything else.

like image 99
Stefan Steinegger Avatar answered Nov 30 '22 20:11

Stefan Steinegger


You should not use base unless you specifically mean "Even if there is a method in this class that overrides the base implementation, I want to call the base implementation and ignore the one on this class".

Using base bypasses the virtual dispatch mechanism that is so important in polymorphism by causing a call instruction to be emitted rather than callvirt.

So saying base.Foo() is very, very different in semantics to saying this.Foo(). And you almost always want the latter.

like image 24
Greg Beech Avatar answered Nov 30 '22 18:11

Greg Beech