Unable to call parameterized constructor for type arguments in Generic class.

I've tried to define a generic class, that uses a type argument  derive from the specified base class without parameterless constructor.
The sample code is the following:

    public class KeywordsSearchTestGeneric<T> where T : Keywords//',new()

    {

        // Methods

        public void ExactMatchCases()

        {

            T keywords1 = new T("string");

        }

    }

    public class Keywords

    {

        // Methods

        public Keywords()

        {

            throw new  NotSupportedException();

        }

        public Keywords(string connString)

        {

            Debug.WriteLine("Keywords " + connString);

        }

    }

    public class DerivedKeywords : Keywords

    {

        // Methods

        public DerivedKeywords(string connString):base(connString)

        {

            Debug.WriteLine("DerivedKeywords " + connString);

 

        }

    }

 However it causes Compiler Error CS0304 “Cannot create an instance of the variable type 'type' because it does not have the new() constraint“.
I beleive that the error is irrelevant, because new Constraint (C#) specifies that any type argument in a generic class declaration must have a public parameterless constructor, but my class has a constructor with parameters.
However I've added new Constraint to the generic class declaration

    public class KeywordsSearchTestGeneric<T> where T : Keywords,new()

but it gives me another Compiler Error CS0417.
The description of the error includes suggestion :
If you need to call another constructor, consider using a class type constraint or interface constraint. “.
Unfortunately, i've started with class type constraint , but didn't find a solution.

posted @ Monday, October 02, 2006 12:41 PM

Print

Comments on this entry:

# re: Unable to call parameterized constructor for type arguments in Generic class.

Left by Piet at 10/3/2006 1:29 AM
Gravatar
I had the same problem.

Google directed me to this url:
http://www.codeproject.com/books/EssentialCS20.asp. It 's sample chapeter from Essential C# 2.0, by Mark Michaelis.

Quote:"Constructor Constraints Are Allowed Only for Default Constructors

One way to circumvent this restriction is to supply a factory interface that includes a method for instantiating the type. The factory implementing the interface takes responsibility for instantiating the entity rather than the EntityDictionary itself (see Listing 11.31).
"

# re: Unable to call parameterized constructor for type arguments in Generic class.

Left by Michael Freidgeim at 10/3/2006 8:09 AM
Gravatar
Piet,
Thank you for the good reference.

Your comment:



 (will not be displayed)


 
 
 
Please add 6 and 1 and type the answer here:
 

Live Comment Preview:

 
«December»
SunMonTueWedThuFriSat
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910