T-moty
T-moty

Reputation: 2797

Generic static classes have multiple instances?

Can a static generic class have more than one single instance?

Standard static classes have a single instance, right? Like this:

public static class MyClass
{
    public static string MyString { get; set; }
}

public void ExampleMethod(int id)
{
    if (id > 0)
        MyClass.MyString = id.ToString();
}

Everywhere in my program, MyClass represent a single instance, that is application scoped.

Ok, but, what if MyClass is generic?

public static class MyClass<T>
{
    public static string MyString { get; set; }
    public static T MyT { get; set; }
}

Means that for each type argument specified, my application scope will create a new instance? Or it will create a separate instance for each possible type argument? (i really hope that it doesn't)

For logic, it cannot still be a single instance, because i can do:

public void ExampleMethod(int id)
{
    MyClass<int>.MyT = id;
    MyClass<DateTime>.MyT = DateTime.Now;
    MyClass<string>.MyT = "Hello, World";
    MyClass<DayOfWeek>.MyT = DayOfWeek.Monday;
}

Thanks in advance for all replies

UPDATE - Microsoft .Net Team already use that

Accidentally, i found an example of usage of a static generic class, built into mscorlib DLL:

// Decompiled with JetBrains decompiler
// Type: EmptyArray`1
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// MVID: 7D59CE68-D0F6-428F-B71C-C8D703E59C19
// Assembly location: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll

internal static class EmptyArray<T>
{
  public static readonly T[] Value = new T[0];
}

The presence of that class means that application-scope will create an empty array, if is not already created for a given type (maybe arrays are memory-hunters objects).

Upvotes: 6

Views: 2003

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Patrick already got the solution, I just add some information.

Actually when your class is static there are no instances of it at all, no matter if the class is generic or not. However what you mean is that all the implementations of the generic class - for instance MyClass<int>, MyClass<string> and so on - are completely different types that are compiled to different classes and do not know anything on each other, they do not even implement the same base-class.

Upvotes: 3

Patrick Hofman
Patrick Hofman

Reputation: 156978

Yes, on the fly a non-generic version of the generic class is generated. That means that every static variable is static within the context of the generated non-generic version (yes, another Type) of your generic class.

To work around this intended behavior, you could create an singleton pattern class outside the generic class where you put all static variables in that should be shared across all versions.

Upvotes: 6

Related Questions