© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
73 replies
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  { }
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
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

❔ Must create DependencySource on same Thread as the DependencyObject
C#CC# / help
3y ago
Class with same name as namespace
C#CC# / help
2y ago
TaskCompletionSource.SetResult() executes on the same thread as the waiting one [Answered]
C#CC# / help
4y ago
✅ idk why when the form is maximize, it stays as the same size.
C#CC# / help
15mo ago