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