how to make static field in generic type c# but so it created only once for type, not…
- User
how to make static field in generic type c# but so it created only once for type, not generic
- Assistant
In C#, static fields in a generic class are shared across all instances of the class regardless of the generic type parameter. However, if you want to ensure that a static field is created only once per type and not per specialization of the generic type, you can utilize a non-generic base class to hold that static field.
Here’s how you can achieve it:
- Define a non-generic base class with the static field:
csharppublic class GenericBase { public static int StaticField; }- Create a generic class inheriting from the non-generic base class: