JetBrains Rider 2021.2 Help

Code Inspection: Access to a static member of a type via a derived type

This error arises in code that accesses a static member of a type via a type that was derived from it. For example:

class A { public static int N; } class B : A { } static void Main(string [] args) { B.N = 3; // warning here }

The above code leads to the erroneous perception that the field N belongs to the type B, whereas it does not. Furthermore, if types A and B are introduced in different assemblies, then the Main() method would introduce an unneeded dependency to B 's assembly, which could otherwise be avoided.

An even more confusing situation can arise from the call to a factory method. If you define a variable with var, the type you get may not be what you would expect. For example

var request = HttpWebRequest.Create("http://someplace.com");

The above code suggests that the result of the Create() operation is an object of type HttpWebRequest whereas it's not actually the case - the result is of type WebRequest and is best written as follows:

var request = WebRequest.Create("http://someplace.com");

Also, C# compiler creates call to method using declaring type, so in IL it will in fact be call to base type. If you add method with the new modifier and same signature to derived type later, code behaviour will not change unless recompiled.

Last modified: 08 March 2021