> Ie. why isn't this allowed:
public class Collection<T> where T: SomeBaseClass, new(Session)
The new() constraint is used to ensure that a new instance of the class can
be created, and not the signature of the generic parameter's constructor.
Se §20.8.2 of the C# 2.0 spec for more info.
to make sure the type has a constructor with a Session parameter?
You can do this by using a static constructor on your generic type. The following
example constrains the generic T parameter to have a constructor that accepts
a single string argument:
public class ConstrainedCtorExample
{
public static void Main()
{
ConstrainedClass<ClassWithStringCtor> c=new ConstrainedClass<ClassWithStringCtor>();
Console.WriteLine("ConstrainedClass<ClassWithStrin gCtor> OK");
try
{
ConstrainedClass<ClassWithoutStringCtor> c=new ConstrainedClass<ClassWithoutStringCtor>();
}
catch (Exception)
{
Console.WriteLine("ConstrainedClass<ClassWithoutSt ringCtor> OK");
}
}
}
public class ClassWithStringCtor
{
public ClassWithStringCtor(string s)
{
}
}
public class ClassWithoutStringCtor
{
public ClassWithoutStringCtor()
{
}
}
public class ConstrainedClass<T>
{
static ConstrainedClass()
{
if (typeof(T).GetConstructor(new Type[] {typeof(string)}) == null)
{
throw new Exception(string.Format("The type '{0}' does not have a constructor
accepting a string argument",typeof(T).Name));
}
}
}
Regards,
Anders Norås
http://dotnetjunkies.com/weblog/anoras/