I've once written a piece of code to add a name to a Task. The code below seems to do the same, but with less code. But I wonder, is it legit. Is it production code ready. What about garbage collection? What about the instance of the class being moved around in code (because it is not pinned), will it still work when it is moved around? How can I put this code to the test?
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var obj = new object();
obj.Tag("Link some data");
var tag = obj.Tag();
}
}
public static class ObjectExtensions
{
private class Tagger
{
public string Tag { get; set; }
}
[StructLayout(LayoutKind.Explicit)]
private struct Overlay
{
[FieldOffset(0)]
public Tagger Tagger;
[FieldOffset(0)]
public object Instance;
}
public static string Tag(this object obj)
{
var overlay = new Overlay {Instance = obj };
return overlay.Tagger.Tag;
}
public static void Tag(this object obj, string tag)
{
var overlay = new Overlay {Instance = obj };
overlay.Tagger.Tag = tag;
}
}
}