Ambigous extension method GetValueOrDefault when porting from .NET Framework to .NET

133 views Asked by At

While porting my (large) application from .NET Framework 4.X to .NET 5+, stumbled over the new System.Collections.Generic.CollectionExtensions, which did not exist in the .NET Framework. Before it existed, I created an extension method GetValueOrDefault, which has a similar signature as the new one - but with the difference that I check for null keys and returned the default value in that case instead of throwing an exception.

In some cases, I got an ambigous match - however not always (presumably because my method has a default parameter for the value). Now, the .NET version is used most of the time and my application crashes everywhere...

Is there any way to globally hide the extension method or to always prefer my version?

PS: I know there exists a similar question (Ambiguous extension method), but it is already quite old, dating before .NET core

Regarding Renaming: Actually, I don't want to rename my method.

  1. It existed before .NET Core
  2. When I rename it, I may accidentally call the .NET version (I am used to this name for years), which may throw an exception when I don't expect it. I don't see any real use case when it would be useful for this method to throw instead of returning the default value.
1

There are 1 answers

9
Jon Skeet On

I would say the simplest fix here is to rename your extension method (e.g. NullKeySafeGetValueOrDefault), and change your code everywhere.

Even if there's a subtle way of getting the compiler to prefer your version, it's much better to be unsubtle about it. Anywhere someone is reading the code, they should be left in no doubt at all which method is going to be called.