Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "Do not access a static member that is defined in a base class from a derived class."

Microsoft's article on C# Coding Conventions (C# Programming Guide) explicitly states:

"Do not access a static member that is defined in a base class from a derived class."

Why should you not access the static member?

It seems like there are valid scenarios where this should happen, for example all const members are static. Should derived classes never be able to read a const member defined in the base class?

like image 464
Rich Avatar asked May 13 '14 13:05

Rich


1 Answers

Let's use object.ReferenceEquals as an example. Here are a few ways you can call this method from a derived class:

class A {
 A() {
  ReferenceEquals("a", "b"); //your warning is based on this style
  object.ReferenceEquals("a", "b"); //recommended style
 }
}

The fact that ReferenceEquals is accessible in A is just a coincidence. A static method is independent of any inheritance hierarchy. Therefore, always call it fully qualified from anywhere.

This warning is just about style and clarity. All the variants I showed compile to the same IL.

A different interpretation would be that you are misusing inheritance to shorten the syntax used to invoke a method. This is an abuse of inheritance. ASP.NET MVC does this with the Controller base class. It allows you to write return View();. It uses inheritance to make a set of methods conveniently available.

like image 70
usr Avatar answered Sep 24 '22 08:09

usr