I am looking for a way to declare a variable such that it exists once
per class, kind of like static, but derived classes would also receive
a new instances of the variable because they are different classes.
Example:
public class MyBaseClass
{
public static int i = 0;
}
public class MyDerivedClass : MyBaseClass
{
}
public class test
{
static void main (...)
{
MyBaseClass obj1 = new MyBaseClass();
MyDerivedClass obj2 = new MyDerivedClass();
obj2.i = 57; //Now obj1.i also equals 57 even though it is an instance of a different class (which I don't want)
}
}
In the example above I have two different objects of two
different classes, and when I set the "i" value of one, it sets the "i"
value of all. What I would like is for all instances of MyBaseClass
to share an "i" value. And all instances of MyDerivedClass to share an
"i" value. But instances of MyBaseClass do not share the "i" value
with instances of MyDerivedClass.
The only thing I can think of is to make MyBase a generic (a template class), but that complicates things elsewhere. Any ideas?
Thanks,
Jeff Plummer
Loading
AlanPosted Jul 27, 2008, 5:49 AM
The simplest solution is to just hide the public static field inherited from the base class:
using System;
public class MyBaseClass
{
public static int i = 3;
}
public class MyDerivedClass : MyBaseClass
{
new public static int i = 1;
}
public class Test
{
static void Main()
{
Console.WriteLine(MyBaseClass.i); // 3
Console.WriteLine(MyDerivedClass.i); // 1
Console.ReadKey();
}
}
Darrell PlankPosted Jul 27, 2008, 5:21 AM
I think the best you can do is to keep track of your values in a static dictionary which maps from types to values and then use that table in a public property. The Set would just retrieve the type of the current object and use it to map into the dictionary and retrieve the value. The Get would use the current object's type to see if the key already exists in the dictionary. If not, return the default value, if so, return the value in the dictionary. Example code: