Inheritance of static members in the CLR spec vs the C# spec


T

Tim Van Wassenhove

Hello,

When i read the CLI spec, 8.10.2 Method inheritance i read the
following:

"A derived object type inherits all of the instance and virtual methods
of its base object type. It does not inherit constructors or
static methods...."

In the C# spec, 17.2.1 Inheritance i read the following:

"A class inherits the members of its direct base class. Inheritance means
that a class implicitly contains all members of its direct base class,
except for the instance constructors, finalizers, and static constructors
of the base class"

Consider the following code:
class A { public static void Method1() { } public static int X = 5;}
class B : A { }

Now i call B.Method1, which is translated to a call A.Method1 in IL.

The C# spec seems to mention that "static" means that members are
related to a specific type, instead of instances...

If C# really inherits all members, wouldn't that mean that the following
code should output 5 instead of the 10?
B.X = 10; Console.WriteLine(A.X);


To come to my question: Am i right when i say that in C# there isn't
true inheritance of static members?
 
Ad

Advertisements

T

Tim Van Wassenhove

[snip large answer]

Thanks for your answer, i've been thinking it all over (drawing a couple
of venndiagrams and doing some proposition logic) and now i can see how
inheritance in c# maps to inheritance in the cli...
 
Ad

Advertisements

J

Jon Skeet [C# MVP]

GlennDoten said:
I wouldn't say "translated." The IL emitted by the compiler is what it
is because A.Method1 and B.Method1 are the very same thing because
Method1 is static.

<snip>

There are two issues here:

1) If the IL call were to B.Method1, that would force type B to be
initialized. By calling A.Method1 instead, type B can remain
uninitialized. This difference has been very significant to some people
in the past.

2) If a new B.Method1 is introduced without recompilation of the
calling code, that new method won't be called with the IL generated by
C#, but would if it generated IL calling B.Method1.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top