Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type parameter in .net(C#) whose value can by one of specified types?

Tags:

c#

.net

generics

Lets say I have classes ClassA, ClassB, ClassC. All of them inherit from object and non of them implements any interface.

Is it possible in C# to declare generic interface that will take generic argument T and that T may be either ClassA or ClassB or ClassC ?

So I would have something like

public interface MyInterface<T> where T: ClassA | ClassB | ClassC {
    ...
}

If it is possible what's the syntax?


Note: I know I could have those classes ClassA, ClassB, ClassC to implement some interface and than use it as constrain of T but before I create an interface that have no methods I want to know that there is no better way.

like image 398
Rasto Avatar asked Nov 28 '25 09:11

Rasto


2 Answers

There is no better way.

You can only specify one base class or interface as that constraint.

But let me ask you this, why are you constraining to those 3 classes if they have nothing in common? Since you say you could constrain to an interface with no methods, what are you actually using from those classes?

With an interface constraint, the only thing you know is that the object used implements that interface.

like image 160
Lasse V. Karlsen Avatar answered Nov 29 '25 22:11

Lasse V. Karlsen


That's not possible, because a type must meet all the constraints, not just one.
Anyway, if your interface wouldn't have a single method in it, it means that your classes have nothing in common. So how would you use them in your generic method anyway?
I think you are missing something important or didn't tell us the whole story.

like image 23
Daniel Hilgarth Avatar answered Nov 29 '25 23:11

Daniel Hilgarth