Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 796
Swim Avatar asked Mar 18 '09 21:03

Swim


People also ask

Can we have non static method in a static class in C#?

Static class always contains static members. Non-static class may contain both static and non-static methods. Static class does not contain an instance constructor.

Are static members inherited C++?

Quick A: Yes, and there are no ambiguity with static members.

What is the advantage of static class in C#?

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created. Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object.

How many copies of a class static member are shared between objects of the class?

We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class.


Video Answer


2 Answers

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.

like image 91
Greg Beech Avatar answered Oct 20 '22 20:10

Greg Beech


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.

like image 30
P Daddy Avatar answered Oct 20 '22 20:10

P Daddy