Question

Call ObjectIDGenerator method twice on reference type, the id values are same.

test a = new test();//reference type
bool isFirstTime;
ObjectIDGenerator IDGenerator = new ObjectIDGenerator();
long theID = IDGenerator.GetId(a, out isFirstTime);
Console.WriteLine(theID);
Console.WriteLine(isFirstTime);

theID = IDGenerator.GetId(a, out isFirstTime);
Console.WriteLine(theID);
Console.WriteLine(isFirstTime);

the output as follows:
1
True
1
False

the object 'a' has only one id.

But when calling the ObjectIDGenerator method on value type, things seem weird.

int a = 100;//value type
bool isFirstTime;
ObjectIDGenerator IDGenerator = new ObjectIDGenerator();
long theID = IDGenerator.GetId(a, out isFirstTime);
Console.WriteLine(theID);
Console.WriteLine(isFirstTime);

theID = IDGenerator.GetId(a, out isFirstTime);
Console.WriteLine(theID);
Console.WriteLine(isFirstTime);

Output:
1
True
2
False

That's why?

Was it helpful?

Solution

i think the essential cause for this is that the int is value types, and the getid() accepts a reference type, so, there needs to be a boxing process. everytime you boxing, you get a new id of the boxed int(not the original one).

hope this will help you.

OTHER TIPS

I think the answer must be that this class (ObjectIDGenerator) is not meant to be used with value types. See here from the documentation:

The object references, which uniquely identify each object, are addresses in the runtime garbage-collected heap.

Of course, value types are not stored on the garbage-collected heap, but on the stack. So, according to the above, the ID tracking will not work correctly (by design) with value types like int.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top