Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static members of generic classes shared between types

Tags:

I'm trying to create a generic class which will have some static functions based on the type. Are there static members for each type? Or only where there is a generic used? The reason I ask is I want a lock object for each type, not one shared between them.

So if I had

class MyClass<T> where T:class {     static object LockObj = new object();     static List<T> ObjList = new List<T>(); } 

I understand that ObjList would definitely have a different object created for each generic type used, but would the LockObj be different between each generic instantiation (MyClass<RefTypeA> and MyClass<RefTypeB>) or the same?

like image 253
Spence Avatar asked Aug 09 '10 07:08

Spence


People also ask

Are static variables shared between subclasses?

Yes, Static members are also inherited to sub classes in java.

Are static variables shared by all objects of a class?

A static variable is shared by all instances of a class. Only one variable created for the class.

Do static data members belong to all instances of a class?

static members exist as members of the class rather than as an instance in each object of the class. There is only a single instance of each static data member for the entire class. Non-static member functions can access all data members of the class: static and non-static.

Can two static variables in different class have same name?

No. Variable name must be unique within each scope.


2 Answers

Just check for yourself!

public class Static<T> {     public static int Number { get; set; } }  static void Main(string[] args) {     Static<int>.Number = 1;     Static<double>.Number = 2;     Console.WriteLine(Static<int>.Number + "," + Static<double>.Number); } // Prints 1, 2 
like image 96
tzaman Avatar answered Nov 05 '22 15:11

tzaman


It will be different for each T. Basically, for all different T you will have different type and members are not shared between different types.

like image 30
Giorgi Avatar answered Nov 05 '22 14:11

Giorgi