Created
June 12, 2019 17:40
-
-
Save tompazourek/8439f8a2938961302c21e15dc6af25ff to your computer and use it in GitHub Desktop.
Helper to generate Object IDs for debugging (to identify the same object via a number)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.CompilerServices; | |
public static class DebugHelper | |
{ | |
private static readonly ConditionalWeakTable<object, object> _objectIds = new ConditionalWeakTable<object, object>(); | |
private static int _lastObjectId; | |
private static readonly object _lock = new object(); | |
public static string GetObjectId(object obj) | |
{ | |
if (obj == null) | |
return "null"; | |
if (_objectIds.TryGetValue(obj, out var objectId)) | |
return $"#{objectId}"; | |
lock (_lock) | |
{ | |
if (_objectIds.TryGetValue(obj, out objectId)) | |
return $"#{objectId}"; | |
_objectIds.Add(obj, ++_lastObjectId); | |
if (_objectIds.TryGetValue(obj, out objectId)) | |
return $"#{objectId}"; | |
throw new Exception("Couldn't generate object Id."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment