Search code examples
c#classinheritancethisradix

C# coding for inherited class set — is it a good practice to use keywords 'base.methodname and this.methodname'?


I have been working in C# for quite some time but come around this perennial question with colleagues now and then.

The question is: In an inherited class set -- when calling a method should we use keywords 'base.methodname and this.methodname'... irrespective of whether it is a overridden method or not?

My answer is: YES -- its a good practice -use it because that is why those were created for.

Detailed explanation: Moreover the code is likely to undergo changes in terms of logic and maybe some IF-ELSE like conditions may come-in at a later date. So at that time, the developer has to be compelled to revisit each line of code and ensure that he/she makes the right choice of which method is being called --- base.methodname() or this.methodname() ELSE the .NET framework will call the DEFAULT (i think its base.methodname()) and the entire logic can go for a toss.

What do other C# programmers think about it?


Solution

  • Whether or not you use "this." is a matter of opinion. Some like it because it is clear that you are calling something class level, others feel it is redundant noise.

    As for base - in my opinion you should only explicitly say "base." if you want to call the base method explicitly and not an overridden method in the current class. Quite often the only place you should even see it is in the overridden method itself.

    Don't call base just because it is the implementation in the base class that will be called. It is not meant to be a way of saying "I know the actual implementation is in the base class", it is meant to be a way of saying "specifically do not call the implementation in this class, call the base one". To use it in any other way partly defeats the point of inheritance.