Search code examples
c#lambdadefault-constructor

How to write conditional instantiation in C#


I have a below lambda default Employee constructor which is working fine.

this.For<IEmployee>().Use(() => new Employee());

Now I want to call another another constructer based on flag value.
If flag is true call Employee constructor with parameter.
If flag is false call default constructor.

this.For<IEmployee>().Use(
if (flag)
{
    () => new Employee("Test");
}
else
{
    () => new Employee());
});

Solution

  • this.For<IEmployee>().Use(() => flag ? new Employee("Test") : new Employee());