Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active February 19, 2020 03:26
Show Gist options
  • Save Porges/99c3c066074e5a3b4d8981fbc6b168a7 to your computer and use it in GitHub Desktop.
Save Porges/99c3c066074e5a3b4d8981fbc6b168a7 to your computer and use it in GitHub Desktop.
for years i have searched for a usecase for recursive delegate signatures
delegate void Normalizer(object obj, Normalizer currentHead);
private static Normalizer _normalize = (obj, currentHead) =>
{
var type = obj.GetType();
var normalizer = BuildNormalizeActionForObjectType(type);
Normalizer newHead = (obj, futureHead) =>
{
if (obj.GetType() == type)
{
normalizer(obj);
}
else
{
currentHead(obj, futureHead);
}
};
var foundHead = Interlocked.CompareExchange(ref _normalize, newHead, currentHead);
if (foundHead != currentHead)
{
// exchange did not occur as _normalize has been overwritten, try again from the top
foundHead(obj, foundHead);
}
};
public static void Normalize(object o)
{
var n = _normalize;
n(o, n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment