I'm using Type.GetConstructor(Type.EmptyTypes)
to get the default constructor for a class. It works if the class has a default constructor with no parameters (class A
). But it doesn't work if a class has a constructor with all parameters optional (class B
). Program doesn't know what the optional parameters are because it only needs the default constructor. What can statements can I use to make it work for both cases? Thanks, appreciate any help!
public class A
{
public A() {}
}
public class B
{
public B(int i = 0, string str = "") {}
}
To get the one that has more optional parameters or an empty constructor at all, use:
typeof(myClass)
.GetConstructors()
.OrderBy(x => x.GetParameters().Length - x.GetParameters().Count(p => p.IsOptional))
.FirstOrDefault();
Say I have the following class:
public class SomeClass
{
public SomeClass()
{
}
public SomeClass(int x)
{
}
public SomeClass(int x = 0, int y = 0)
{
}
}
Basically, you're asking for a query that will find the constructors that match constructor 1 and 3 above? If so, use this:
var constuctors = typeof(SomeClass).GetConstructors()
.Where(x => x.GetParameters().Count() == 0
|| x.GetParameters().Count(param => param.GetCustomAttributes(typeof(OptionalAttribute), false).Count() > 0) == x.GetParameters().Count());
Incredibly nasty query, but it gets the job done returning only 1 and 3 above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With