Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generic methods, type parameters in new() constructor constraint

Tags:

Is there a way to create a Generic Method that uses the new() constructor constraint to require classes with constructors of specific types?

For Example:

I have the following code:

public T MyGenericMethod<T>(MyClass c) where T : class {     if (typeof(T).GetConstructor(new Type[] { typeof(MyClass) }) == null)     {         throw new ArgumentException("Invalid class supplied");     }     // ... } 

Is it possible to have something like this instead?

public T MyGenericMethod<T>(MyClass c) where T : new(MyClass) {     // ... } 

EDIT: There's a suggestion regarding this. Please vote so we can have this feature in C#!

like image 206
Meryovi Avatar asked Jul 29 '10 15:07

Meryovi


2 Answers

Not really; C# only supports no-args constructor constraints.

The workaround I use for generic arg constructors is to specify the constructor as a delegate:

public T MyGenericMethod<T>(MyClass c, Func<MyClass, T> ctor) {     // ...     T newTObj = ctor(c);     // ... } 

then when calling:

MyClass c = new MyClass(); MyGenericMethod<OtherClass>(c, co => new OtherClass(co)); 
like image 138
thecoop Avatar answered Sep 22 '22 13:09

thecoop


No. Unfortunately, generic constraints only allow you to include:

where T : new() 

Which specifies that there is a default, parameterless constructor. There is no way to constrain to a type with a constructor which accepts a specific parameter type.

For details, see Constraints on Type Parameters.

like image 45
Reed Copsey Avatar answered Sep 22 '22 13:09

Reed Copsey