Skip to content

Instantly share code, notes, and snippets.

@tompazourek
Created June 12, 2019 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tompazourek/8439f8a2938961302c21e15dc6af25ff to your computer and use it in GitHub Desktop.
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)
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