Ambiguous extension method

C#.Net

C# Problem Overview


I am making the following call to an extension method:

database.ExecuteScalar(command).NoNull<string>(string.Empty);

I get an error that the extension method is ambiguous .

I have two dlls with the same code that implement NoNull(string str) under different namespaces.

How can I explicitly refer to one namespace?

How would I have it done if it was the same namespace?

Update: I cannot rewrite the 3rd party dlls.

C# Solutions


Solution 1 - C#

  1. Remove the ambiguity by redefining or eliminating one of the methods at the source. You don't need redundancy.
  2. If you do not control the source, include only one of them in your class file via the using directive.
  3. If you still need both namespaces in the given class file, invoke the version you wish simply as a static class call, unambiguously identifying the method via the (potentially fully qualified) class name.
 Abc.Xyz.ExtensionsClass.NoNull(database.ExecuteScalar(), string.Empty);
 // <Abc.Xyz.> is only necessary if the classes themselves match names
 // if not, only <ClassName>.<MethodName> is needed

Solution 2 - C#

Just in case somebody will need this...

Ambiguity can be resolved if concurrent namespaces which have extension methods with same name, are included at different levels (most inner included namespace will have priority).

For example:

using Namespace1;
namespace MyApplication 
{
    using Namespace2;
    ...
    db.Execute(); // Namespace2 Execute() will be called
}

Solution 3 - C#

I would strongly suggest that you rename one of the extension methods. Depending on what else you do, you could possibly just remove the using directive for one of those namespaces, but that won't help if you need both namespaces for other things. (This leads to a suggestion to put extension methods in their own namespace, of course.) Renaming is likely to simplify things in general though.

Solution 4 - C#

You should change the signature of one (or both of them) to differentiate what it does. This seems like duplication of code somewhere unless these do different things. Though if they do different things I would think you would differentiate that in the names. I'd recommend creating some sort of enumeration (a flag maybe) to pass as an extra argument to one of the methods.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElad BendaView Question on Stackoverflow
Solution 1 - C#Anthony PegramView Answer on Stackoverflow
Solution 2 - C#pakeha_byView Answer on Stackoverflow
Solution 3 - C#Jon SkeetView Answer on Stackoverflow
Solution 4 - C#Joel EthertonView Answer on Stackoverflow