Share a static variable across constructed generic types ?

  • Thread starter Thread starter Samuel R. Neff
  • Start date Start date
S

Samuel R. Neff

Is there any way to declare a static variable within a generic type
definition and have that variable be shared across all constructed
generic types?

For example, how can I modify this code:

private class C<T>
{
public static int Counter = 0;
}

public static void Test()
{
Console.WriteLine(++C<int>.Counter);
Console.WriteLine(++C<string>.Counter);
Console.WriteLine(++C<double>.Counter);
}

Which prints out

1
1
1

To instead print out

1
2
3

Thanks,

Sam
 
Samuel R. Neff said:
Is there any way to declare a static variable within a generic type
definition and have that variable be shared across all constructed
generic types?

For example, how can I modify this code:

private class C<T>
{
public static int Counter = 0;
}

public static void Test()
{
Console.WriteLine(++C<int>.Counter);
Console.WriteLine(++C<string>.Counter);
Console.WriteLine(++C<double>.Counter);
}

using a different, non-generic class, like this:

private static class SharedC
{
internal static int Counter = 0;
}

private class C<T>
{
public static int Counter { get { return SharedC.Counter; } set {
SharedC.Counter = value; } }
}
 
Is there any way to declare a static variable within a generic type
definition and have that variable be shared across all constructed
generic types?

No, so you probably have to put the field in another non-generic
class.


Mattias
 
No, the generic classes you create are separate classes, so they have
separate static storage.

Put the static variable in a separate class that is not generic, and use
that from the generic classes.
 
Back
Top