Share a static variable across constructed generic types ?

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
 
B

Ben Voigt

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; } }
}
 
M

Mattias Sjögren

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
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top