Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generics - Constraints on type parameters

Tags:

c#

generics

I'm trying to build a factory method that uses the generics feature of C#.

In this factory method I would like to constraint it to some specific classes, all of which do not have a default constructor.

Here is my example. Can someone tell me if it's possible to run it?

public class AbstractClass {
    //this abstract class does not have a default constructor, nor its subclasses
    public AbstractClass(SomeClassName obj) {
        //use obj for initialization
    }
}

//this factory class should create objects of type T that inherit 
//from AbstractClass and invoke the non-default constructor
public class FactoryClass {
    public static T BuildObject<T> (SomeClassName obj) where T: AbstractClass {
        return new T(obj); //does not work?!?!?!
    }
}


//Edit: ANSWER!!!
public static T BuildObject<T>(SomeClassUsedForTheConstructor item) where T : SomeAbstractClass { 
return (T) Activator.CreateInstance(typeof (T), item); 
} 
like image 857
Pablo Avatar asked Sep 16 '09 18:09

Pablo


1 Answers

I like to use Activator.CreateInstance(typeof(T)) in my generics that need to create new objects of type T. It works really well.

like image 130
Brian Genisio Avatar answered Sep 22 '22 02:09

Brian Genisio