Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring resolution to ambiguous constructor reference

Tags:

c#

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)
        {

        }
    }
like image 966
Adam G Avatar asked Aug 05 '26 20:08

Adam G


2 Answers

Maybe use a static method ala named constructor idiom:

class Foo
{
    ...
    public static Foo Create(Func<IBar> func)
    {
        return new Foo(func());
    }
}
like image 133
Ilian Avatar answered Aug 08 '26 09:08

Ilian


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;
}
like image 27
Sweeper Avatar answered Aug 08 '26 10:08

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!