How to print an object identifier?

`I need to know if two links from completely different parts of the program refer to the same object. I cannot compare links programmatically because they are from different contexts (one link is not visible from another and vice versa).

Then I want to print a unique identifier for each object using Console.WriteLine() . But the ToString() method does not return a "unique" identifier, it simply returns a "class name".

Is it possible to print a unique identifier in C # (e.g. in Java)?

+6
source share
4 answers

The closest that you can easily get (which will not be affected by moving GC objects around, etc.) is probably RuntimeHelpers.GetHashCode (Object) . This gives a hash code that will be returned by calling Object.GetHashCode() not virtually on the object. However, this is not a unique identifier. This is probably good enough for diagnostic purposes, but you should not rely on it to compare products.

EDIT: if this is for diagnostic purposes only, you can add a kind of “canonical image generator” that was just a List<object> ... when you ask for the identifier of an object, you should check if it already exists in the list (by comparing the links ), and then add it to the end if it is not. The identifier will be the index in the list. Of course, doing this without introducing a memory leak will be due to weak links, etc., but as a simple hack, this may work for you.

+16
source

one link is not visible from another and vice versa

I do not buy it. If you couldn’t even get pens, how would you get their identifiers?

In C #, you can always handle objects, and you can always compare them. Even if you need to use reflection to do this.

+2
source

If you need to know if two links point to the same object, I will simply write this .

By default, the == operator checks referential equality. This is done by determining whether two links point to the same object. Therefore, reference types do not need the == operator to get this functionality.

So, the == operator will do the trick without doing the Id workaround.

+1
source

I assume that you call ToString in your object reference, but it is not clear that this or your explained situation is TBH, so just carry me.

Does the type provide an ID property? If yes, try the following:

 var idAsString = yourObjectInstance.ID.ToString(); 

Or, type directly:

 Console.WriteLine(yourObjectInstance.ID); 

EDIT:

I see that John saw this directly through this problem, and my answer looks rather naive - regardless of whether I leave it, if only to emphasize the lack of clarity of the question. And also, maybe suggest skipping down on John’s expression: “This [ GetHashCode ] is still not a unique identifier” if you decide to expose your own uniqueness using an identifier.

0
source

Source: https://habr.com/ru/post/886144/


All Articles