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

StackOverflow https://stackoverflow.com/questions/23632586

  •  21-07-2023
  •  | 
  •  

Pregunta

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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top