Static fields in generic classes

Cross posted from https://dev.givetheiron.se/2019/06/12/static-fields-in-generic-classes/

In a new attempt to reboot my blogging I’m putting my exploratory coding sessions in writing (although I’m not sure I can call it reboot, since I’m not sure I booted my blogging to begin with). With exploratory coding I mean that when I come across a question I have, instead of immediately searching for the answer, I try and explore it with code instead. I use LINQPad since it’s so fast to get up and running. So over to the question.

Question: Static fields are shared in all instances of a class, but what happens if the class is a generic class?

The specific problem I had was I’m storing a token in a static string, but I didn’t want the token to be shared between different concrete types. So, in the following code, would the StaticString be shared between GenericClass<int> and GenericClass<string>?

void Main()
{
    GenericClass<int>.StaticString = "genericInt";
    GenericClass<string>.StaticString = "genericString";
    GenericClass<int>.StaticString.Dump();
    GenericClass<string>.StaticString.Dump();
}

public class GenericClass<T>
{
    public static string StaticString { get; set; }
}

The result is good for me for the problem I have

I'm a GenericClass<int> StaticString
I'm a GenericClass<string> StaticString

As you can see by the result, they aren’t shared. Now I remember from way back I read that Generics in the Run Time work differently with value types and reference types (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generics-in-the-run-time) so to be sure I test with another reference type as well.

    ...
    GenericClass<Exception>.StaticString = "I'm a GenericClass<Exception> StaticString";
    GenericClass<Exception>.StaticString.Dump();

And the result is more of the same

I'm a GenericClass<int> StaticString
I'm a GenericClass<string> StaticString
I'm a GenericClass<Exception> StaticString

I could have added unit tests to verify this, but it seems unnecessary to have unit tests covering the C# language. I just needed to check how the language behaves for generics.

Lämna en kommentar