C#C
C#3y ago
Catsillas

❔ AllOf<>? Something along the same lines as discriminated unions?

Essentially I am trying to write a generic class that is something like this:


public class MyClass<T> {

  AllOf<T, MyOtherClass> Value { get; set; }
  
}

// some function
void Test() {
  MyClass<IEquatable> m = new MyClass<IEquatable>();
  
  m.Value = new SomeClassA(); // compile error, does not inherit MyOtherClass
  m.Value = new SomeClassB(); // compile error, does not implement IEquatable
  m.Value = new SomeClassC(); // success

}


public class SomeClassA : IEquatable { }
public class SomeClassB : MyOtherClass { }
public class SomeClassC : MyOtherClass, IEquatable  { }



Is there absolutely not way to get this to resolve at compile time? I suspect not, but who knows what kind of crazy ideas people can come up with


My current best idea is this, but id like to avoid having to have the setter, but worst case scenario this will probably do the trick
image.png
Was this page helpful?