22

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?

Spence
  • 28,526
  • 15
  • 68
  • 103

3 Answers3

17

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
BrutalDev
  • 6,181
  • 6
  • 58
  • 72
tzaman
  • 46,925
  • 11
  • 90
  • 115
  • I was worried about corner cases. Still you tdd guys seem to have your heads in the right spot – Spence Aug 09 '10 at 22:20
  • @tzaman can you explain this then: http://stackoverflow.com/questions/35048279/protected-static-string-accessability-issue-in-c-sharp?noredirect=1#comment57871825_35048279 – bpeikes Jan 29 '16 at 02:09
7

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.

Giorgi
  • 30,270
  • 13
  • 89
  • 125
4

Instantiated generic types in C# are actually different types at runtime, hence the static members will not be shared.

Igor Zevaka
  • 74,528
  • 26
  • 112
  • 128
  • 1
    I was worried because my understanding was that each value type got a different set of code but reference types used the same "generic" set of code with a different type constraint. Just checking for corner cases. – Spence Aug 10 '10 at 02:30