Using a class's static member on a derived type?

C#StaticResharper

C# Problem Overview


Using Resharper 4.1, I have come across this interesting warning: "Access to a static member of a type via a derived type". Here is a code sample of where this occurs:

class A {
    public static void SomethingStatic() {
       //[do that thing you do...]
    }
}

class B : A {
}

class SampleUsage {
    public static void Usage() {
        B.SomethingStatic(); // <-- Resharper warning occurs here
    }
}

Does anybody know what issues there are (if any) when making use of A's static members via B?

C# Solutions


Solution 1 - C#

One place where it might be misleading is when the static is a factory method, e.g. the WebRequest class has a factory method Create which would allow this type of code to be written if accessed via a derived class.

var request = (FtpWebRequest)HttpWebRequest.Create("ftp://ftp.example.com");

Here request is of type FtpWebRequest but it's confusing because it looks like it was created from an HttpWebRequest (a sibling class) even though the Create method is actually defined on WebRequest (the base class). The following code is identical in meaning, but is clearer:

var request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com");

Ultimately there's no major problem accessing a static via a derived type, but code is often clearer by not doing so.

Solution 2 - C#

B.SomethingStatic() makes the statement that SomethingStatic is a member of B. This is not true. SomethingStatic is unequivocally a member of A. The fact that it's accessible unqualified to members of B (as if it were a member of B) is a matter of convenience. The fact that it's accessible when qualified with a B is, IMO, a mistake.

Solution 3 - C#

It's not a warning, usually, just a suggestion. You're creating a dependency on something unnecessarily.

Suppose you later decide that B doesn't need to inherit A. If you follow Resharper's advice, you won't need to modify that line of code.

Solution 4 - C#

Yeah I've seen this too, I've always assumed it was just warning me because it was unnecessary. A.SomethingStatic(); would do the same thing.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSwimView Question on Stackoverflow
Solution 1 - C#Greg BeechView Answer on Stackoverflow
Solution 2 - C#P DaddyView Answer on Stackoverflow
Solution 3 - C#Daniel EarwickerView Answer on Stackoverflow
Solution 4 - C#RayView Answer on Stackoverflow