Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# thread static fields from generic abstract class

Tags:

c#

generics

I have a generic abstract class with thread static fields, defined as such:

abstract MyClass<T>
{
    [ThreadStatic]
    private static bool A;
}

Once I derive from this class:

MyOtherClass : MyClass<string>

What happens to the field A?

  • Does MyOtherClass have its own thread static fields?
  • or, is there a set of shared thread static fields for all classes derived from MyClass?

And, if the fields are per derived class, if I do this:

MyOtherClass1 : MyClass<string>
MyOtherClass2 : MyClass<bool>
MyOtherClass3 : MyClass<string>

As MyOtherClass1 and MyOtherClass3 have the same types, would the fields be shared?

like image 653
Thomas Avatar asked Mar 13 '26 05:03

Thomas


1 Answers

Derived classes do not have a separate copy of static variables. Usages of a generic class with different generic type arguments however do each have their own copy of static variables. So MyOtherClass1 and MyOtherClass3 will share the same variables, as they have the same generic type arguments for MyClass, and MyOtherClass2 will have a different set of variables because it doesn't share the same generic arguments.

like image 118
Servy Avatar answered Mar 14 '26 19:03

Servy