1

Is something like this even possible. I want the case, that it executes, when T is MyClass or MyOtherClass.

public T Method<T>()
   where T: MyClass, T: MyOtherClass
   { //execution }
3
  • 1
    Why would that be useful? Does MyClass and MyOtherClass have something in common? Commented Sep 7, 2021 at 10:18
  • That wouldn't be particularly generic, though. And no, it's not possible (not counting explicit runtime checks). You could have a MethodMyClass and MethodMyOtherClass. Commented Sep 7, 2021 at 10:20
  • 1
    What are you actually trying to do? It almost looks like you want to use Discriminated Unions, like those found in TypeScript or F#. You can't do this easily in C# yet, not even C# 10, as DUs were pushed to vNext once again. There may be other ways to get the same functionality though Commented Sep 7, 2021 at 10:24

1 Answer 1

3

This is not possible but you can use an interface for this.

For example:

public interface IMyInterface...

public class MyClass : IMyInterface...

public class MyOtherClass : IMyInterface...

public T Method<T>() where T : IMyInterface...
Sign up to request clarification or add additional context in comments.

2 Comments

@PanagiotisKanavos Yes, that's possible to use some constraints, but not 2 classes as the class type should always be the first one. In the question, he wants 2 classes.
I noticed that or only afterr Jeroen Mosfert pointed it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.