Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get default constructor when parameters are optional

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 = "") {}
}
like image 978
dlsou Avatar asked Apr 07 '11 19:04

dlsou


2 Answers

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();
like image 165
jrivam Avatar answered Sep 23 '22 23:09

jrivam


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.

like image 36
Tejs Avatar answered Sep 25 '22 23:09

Tejs