Last active
May 26, 2024 22:49
-
-
Save Sl4vP0weR/ab866110bff59a990ab9d0c733a26b51 to your computer and use it in GitHub Desktop.
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; | |
// 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