I'd like to create an interface that gives objects of certain classes an id and a dictionary where you can find the reference by Id. So every class should have their own counting id (starting at 1).
That is what I have:
interface IIdentifiable<T>
{
public int id { get; }
public static int NextId { get; private set; } = 1;
private static readonly Dictionary<int, T> InstanceById = new Dictionary<int, T>();
public static T GetInstanceById(int id)
{
return InstanceById[id];
}
protected static void AddInstanceById(T instance, int id)
{
InstanceById.Add(id, instance);
}
protected static void IncrementNextId() => NextId++;
}
It works, but I'd like to restrict it in the way so that every class is only allowed to implement the interface that corresponds to the class.
e.g.:
class A : IIdentifiable<A> // how to make sure, that only A is allowed here?
{ }
I know about type restrictions, but they don't suit for this case because they are defined in the interface via (where T : ..) but the interface can't know what class it is currently implemented by.
Is there any way to formulate this restriction? Maybe also using a slightly different architechture?
Thanks!