Consider the following class
class Foo
{
public Foo(IBar bar=null)
{
}
}
I have a need to inject an alternate constructor to allow the IBar instance to be provided on demand rather than injected.
class Foo
{
public Foo(IBar bar=null)
{
}
public Foo(Func<IBar> barFunc) : this((IBar)null)
{
}
}
However there is a bunch of code in several dependent projects like:
Foo foo = new Foo(null);
This code won't compile anymore due to the ambiguous constructor reference.
Obviously I could change the code to
Foo foo = new Foo((IBar)null);
But this would require changes to a whole bunch of projects, and my goal is a transparent change. Is there some way to specify which constructor to call if ambiguous? Or a way to indicate to the compiler that barFunc cannot be null
At the moment, I am looking at this but it feels .... dirty
class Foo
{
public Foo(IBar bar=null)
{
}
public Foo(Func<IBar> barFunc, bool notUsed) : this((IBar)null)
{
}
}
Maybe use a static method ala named constructor idiom:
class Foo
{
...
public static Foo Create(Func<IBar> func)
{
return new Foo(func());
}
}
Make the Foo(Func<IBar>) constructor private, and add a factory method:
public static Foo WithIBarFunc(Func<IBar> func) {
return new Foo(func);
}
If you can, delete the the Foo(Func<IBar>) constructor all together and write the method like this:
public static Foo WithIBarFunc(Func<IBar> func) {
var foo = new Foo(null);
// initialise foo with func...
return foo;
}
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