Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static members of a generic class tied to the specific instance?

This is more of a documentation than a real question. This does not seem to have been addressed on SO yet (unless I missed it), so here goes:

Imagine a generic class that contains a static member:

class Foo<T> {     public static int member; } 

Is there a new instance of the member for each specific class, or is there only a single instance for all Foo-type classes?

It can easily be verified by code like this:

Foo<int>.member = 1; Foo<string>.member = 2; Console.WriteLine (Foo<int>.member); 

What is the result, and where is this behavior documented?

like image 271
mafu Avatar asked Jun 14 '10 12:06

mafu


People also ask

Can a static class be generic?

1 Answer. You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields.

What are instance and static members of a class?

An instance data member of a class is recreated each time when a new instance of the class is created and it is associated with that instance only. Whereas a static data member of a class is not recreated with new instance creation, only one copy of it is shared by all the instances.

Can generic variables be static?

Using generics, type parameters are not allowed to be static. As static variable is shared among object so compiler can not determine which type to used. Consider the following example if static type parameters were allowed.

Can you use generics in static method?

Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.


1 Answers

A static field is shared across all instances of the same type. Foo<int> and Foo<string> are two different types. This can be proven by the following line of code:

// this prints "False" Console.WriteLine(typeof(Foo<int>) == typeof(Foo<string>)); 

As for where this is documented, the following is found in section 1.6.5 Fields of the C# Language Specification (for C# 3):

A static field identifies exactly one storage location. No matter how many instances of a class are created, there is only ever one copy of a static field.

As stated before; Foo<int> and Foo<string> are not the same class; they are two different classes constructed from the same generic class. How this happens is outlined in section 4.4 of the above mentioned document:

A generic type declaration, by itself, denotes an unbound generic type that is used as a “blueprint” to form many different types, by way of applying type arguments.

like image 146
Fredrik Mörk Avatar answered Oct 16 '22 02:10

Fredrik Mörk