cwap
cwap

Reputation: 11277

Static methods on generic classes?

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" :)

Upvotes: 9

Views: 13356

Answers (2)

casperOne
casperOne

Reputation: 74530

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.

Upvotes: 10

Jon Skeet
Jon Skeet

Reputation: 1500275

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.

Upvotes: 22

Related Questions