Skip to content

Instantly share code, notes, and snippets.

@Sl4vP0weR
Last active May 26, 2024 22:49
Show Gist options
  • Save Sl4vP0weR/ab866110bff59a990ab9d0c733a26b51 to your computer and use it in GitHub Desktop.
Save Sl4vP0weR/ab866110bff59a990ab9d0c733a26b51 to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.CompilerServices;
// our code
MyType obj = new();
MyExtension ext = (MyExtension)obj;
ext.MyField = 42;
// other code
ext = (MyExtension)obj;
Console.WriteLine(ext.MyField);
public class MyType;
public class MyExtension
{
private MyType inner;
private MyExtension(MyType @this)
{
inner = @this;
}
private static ConditionalWeakTable<MyType, MyExtension> _Cache = new();
public static explicit operator MyExtension(MyType @this)
{
if(@this is null)
throw new ArgumentNullException(nameof(@this));
MyExtension extension;
lock(_Cache)
{
if(!_Cache.TryGetValue(@this, out extension!))
_Cache.Add(@this, extension = new(@this));
}
return extension;
}
public static explicit operator MyType(MyExtension extension) => extension.inner;
public int MyField;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment