Question: 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](https://stackoverflow.com/questions/2392075/how-can-i-find-out-how-many-objects-are-created-of-a-class), 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?

Answer: 
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>`.
Or a thread safe version

```
public class BaseClass
{
   public static ConcurrentDictionary<Type,int> Counter = new ConcurrentDictionary<Type, int>();   
   public BaseClass() => Counter.AddOrUpdate(GetType(), 1, (type, i) => i + 1);
}

```

**Usage**

```
for (int i = 0; i < 2; i++)
   Console.WriteLine("Creating " + new A());

for (int i = 0; i < 4; i++)
   Console.WriteLine("Creating " + new B());

for (int i = 0; i < 1; i++)
   Console.WriteLine("Creating " + new C());

foreach (var item in BaseClass.Counter.Keys)
   Console.WriteLine(item + " " + BaseClass.Counter[item] );

```

**Ouput**

```
Creating ConsoleApp8.A
Creating ConsoleApp8.A
Creating ConsoleApp8.B
Creating ConsoleApp8.B
Creating ConsoleApp8.B
Creating ConsoleApp8.B
Creating ConsoleApp8.C
ConsoleApp8.A 2
ConsoleApp8.C 1
ConsoleApp8.B 4

```

[Full Threaded Demo Here](https://dotnetfiddle.net/zJjCpd)