I have a base class and several derived classes (for example Base
and ChildA : Base
). Each time I create an instance of ChildA
class, I want it to be assigned a unique instance number (similar to autoincrement IDs in relational databases, but for my classes in memory as opposed to in a database).
My question is similar to this one, but there is one distinct difference: I would like the base class to handle this automatically. For each of my derived classes (ChildA, ChildB, ChildC, etc.), I would like the base class to maintain a separate count and increment this when a new instance of that derived class is created.
So, the information held in my Base
class might end up looking like this:
ChildA,5
ChildB,6
ChildC,9
If I then instantiate a new ChildB (var instance = new ChildB();
), I would expect ChildB to be assigned the id 7, since it follows on from 6.
Then, if I instantiate a new ChildA, I would expect ChildA to be assigned the id 6.
-
How can I handle this within the constructor of my Base
class?
You could use a static Dictionary<Type, int>
inside the base class where you keep track of derived instances by type. Since this
will be of the derived type, you can use this.GetType()
as the key inside the dictionary.
class Base
{
static Dictionary<Type, int> counters = new Dictionary<Type, int>();
public Base()
{
if (!counters.ContainsKey(this.GetType()))
counters.Add(this.GetType(), 1);
else
counters[this.GetType()]++;
Console.WriteLine(this.GetType() + " " + counters[this.GetType()]);
}
}
class Derived : Base
{
}
class Derived2 : Base
{
}
public static void Main()
{
new Derived();
new Derived2();
new Derived();
}
Output:
Derived 1
Derived2 1
Derived 2
For thread safety, you can use a ConcurrentDictionary<K,V>
instead of Dictionary<K,V>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With