How to write conditional instantiation in C#

58 Views Asked by At

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());
});
2

There are 2 best solutions below

2
Dmitry On BEST ANSWER
this.For<IEmployee>().Use(() => flag ? new Employee("Test") : new Employee());
0
David On

Looks like you just have the syntax/structure mixed up. This part of the lambda:

() => 

is the function header. Everything after it is the function body. You're trying to wrap your if structure around that. Which would conceptually be similar to:

if (someCondition)
{
    public Employee SomeFunc() { return new Employee("Test"); }
}
else
{
    public Employee SomeFunc() { return new Employee(); }
}

As you can see, this isn't how to structure code. Instead, move the logic to within the function body. For example:

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

(Which can be refactored to something more compact, but left here for the purpose of illustration.)