Imagine I have a single class, with two instances:
MyClass a = new MyClass();
MyClass b = new MyClass();
MyClass has a method PrintUniqueInstan
Based on the additional information we now have, I believe that you can solve your problem very easily using ConditionalWeakTable (which is only from .NET 4 onwards).
You can therefore create such a global table inside your "manager" class and associate each object with a long
, a Guid
or anything else you might want¹. Whenever your manager encounters an object it can get its associated id (if you have seen it before) or add it to the table and associate it with a new id created on the spot.
¹ Actually the values in the table must be of a reference type, so you cannot use e.g. long
as the value type directly. However, a simple workaround is to use object
instead and let the long
values be boxed.
Isn't this a basic usage example for static
members?
class Foo
{
private static int instanceCounter;
private readonly int instanceId;
Foo()
{
this.instanceId = ++instanceCounter;
}
public int UniqueId
{
get { return this.instanceId; }
}
}
Of course you have to pay attention to the range of identifiers so that you don't start reusing them if billions of instances are created, but that's easy to solve.