views:

45

answers:

1

I've just started using C#4.0(RC) and come up with this problem:

class Class1 { public Class1() { } }
class Class2 { public Class2(string param1) { } }
class Class3 { public Class3(string param1 = "default") { } }

Type[] types = new Type[] { typeof(Class1), typeof(Class2), typeof(Class3) };

// Problem starts here, main-method
for(int i = 0; i < types.Length; i++)
{
    ConstructorInfo ctr = provider.GetConstructor(Type.EmptyTypes);
    Console.WriteLine(ctr == null ? "null" : ctr.Name);
}

Note, I've never tried this actual code, but I've just looked at the results of doing GetConstructor using debugging in VS2010

This is perfect for the two first classes (1 and 2), the first one prints an actual ConstructorInfo-object's name of the parameterless constructor of Class1, the second prints null. However, the problem arises with the third one, because what I actually want isn't to know whether it takes 0 parameters or not, but it's whether Ican create an instance of the class without any parameters. How do I do that?

+1  A: 

I found a way to do it. It's not pretty but it works.

var ctrs = from c in provider.GetConstructors()
           where c.GetParameters().Where(p => !p.IsOptional).Count() == 0
           select c;
ConstructorInfo ctr = ctrs.FirstOrDefault();
Alxandr