Static methods on generic classes?
Solution 1
If the values have nothing to do with the type of the generic base class, then they shouldn't be in the generic base class. They should either be in a completely separate class, or in a non-generic base class of the generic class.
Bear in mind that for static variables, you get a different static variable per type argument combination:
using System;
public class GenericType<TFirst, TSecond>
{
// Never use a public mutable field normally, of course.
public static string Foo;
}
public class Test
{
static void Main()
{
// Assign to different combination
GenericType<string,int>.Foo = "string,int";
GenericType<int,Guid>.Foo = "int,Guid";
GenericType<int,int>.Foo = "int,int";
GenericType<string,string>.Foo = "string,string";
// Verify that they really are different variables
Console.WriteLine(GenericType<string,int>.Foo);
Console.WriteLine(GenericType<int,Guid>.Foo);
Console.WriteLine(GenericType<int,int>.Foo);
Console.WriteLine(GenericType<string,string>.Foo);
}
}
It sounds like you don't really want a different static variable per T
of your generic base class - so you can't have it in your generic base class.
Solution 2
That's exactly what you have to do. When you have a type parameter, each different instantiation of the type is a separate type. This leads to separate static variables.
The only workaround is to have a base class that the generic class derives from.
cwap
Updated on July 27, 2022Comments
-
cwap almost 2 years
Okay, this is the case:
I got a generic base-class which I need to initialize with some static values. These values have nothing to do with the kind of types my generic baseclass is loaded with.
I want to be able to do something like this:
GenericBaseclass.Initialize(AssociatedObject);
while also having a class doing like this:
public class DerivedClass : GenericBaseclass<int> { ... }
Is there any way to accomplish this? I could make a non-generic baseclass and put the static method there, but I don't like that "hack" :)
-
cwap about 15 years"Should" as in "best practice" or "should" as in "the only way to accomplish the desired behavior" ? :)
-
Jon Skeet about 15 yearsIf you only want one static variable despite different type arguments being provided, it's "the only way to accomplish the desired behavior".
-
cwap about 15 yearsThanks for clarifying.. I should've done that my self, sorry about that. Makes perfect sense though :) - Now, go to bed Mr. Know-it-all :P