Reputation: 1253
I know that a generic type will not be shared among instances of different close constructed types. This means that for a generic class C<T>
which has a static field X
, the values of C<int>.X
and C<string>.X
have completely different, independent values.
In my case I really need to have a static field shared between instances with different generic arguments.
The only solution i found was "define a non-generic base class to store your static members, then set your generic type to inherit from this type."
The problem is that my class is already inherit from other .net class.
Is there other way to solve this?
Upvotes: 2
Views: 1261
Reputation: 152566
You could farm the requests off to an internal non-generic class to store the shared data:
public class Bar{}
public class FooGeneric<T> : Bar
{
public static string SharedData {
get {
return Foo.SharedData;
}
set{
Foo.SharedData = value;
}
}
}
internal class Foo
{
public static string SharedData = "Fizz";
}
usage:
Console.WriteLine(FooGeneric<string>.SharedData); // "Fizz"
FooGeneric<string>.SharedData = "Buzz";
Console.WriteLine(FooGeneric<string>.SharedData); // "Buzz"
Console.WriteLine(FooGeneric<int>.SharedData); // "Buzz"
Upvotes: 4
Reputation: 482
Inherit from a non-generic base class that inherits from the other .NET class from which your generic class currently inherits. Store your shared static state there. Of course, this will not work if the other .NET class is itself generic; luckily, you indicated that is not the case.
Upvotes: 1