Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method multiple (OR) type constraint

Reading this, I learned it was possible to allow a method to accept parameters of multiple types by making it a generic method. In the example, the following code is used with a type constraint to ensure "U" is an IEnumerable<T>.

public T DoSomething<U, T>(U arg) where U : IEnumerable<T> {     return arg.First(); } 

I found some more code which allowed adding multiple type constraints, such as:

public void test<T>(string a, T arg) where T: ParentClass, ChildClass  {     //do something } 

However, this code appears to enforce that arg must be both a type of ParentClass and ChildClass. What I want to do is say that arg could be a type of ParentClass or ChildClass in the following manner:

public void test<T>(string a, T arg) where T: string OR Exception { //do something } 

Your help is appreciated as always!

like image 568
Mansfield Avatar asked May 31 '12 12:05

Mansfield


People also ask

Can generic class have multiple constraints?

Multiple interface constraints can be specified. The constraining interface can also be generic. In a nullable context in C# 8.0 and later, T must be a non-nullable type that implements the specified interface.

What are generic type constraints?

C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.

Can a generic class have multiple parameters?

A Generic class can have muliple type parameters.

What does the generic constraint of type interface do?

Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.


1 Answers

That is not possible. You can, however, define overloads for specific types:

public void test(string a, string arg); public void test(string a, Exception arg); 

If those are part of a generic class, they will be preferred over the generic version of the method.

like image 153
Botz3000 Avatar answered Oct 10 '22 20:10

Botz3000