I'm working with some legacy C# code and below are two overloaded methods that I can't change:
void PerformCheck(LegacyData data) {...}
void PerformCheck(object data) {...}
There is some code that uses the above overloaded methods. When that code passes anything but a LegacyData reference, the PerformCheck(object data) gets invoked, e.g. PerformCheck("Hello World"); However, if null is passed, PerformCheck(LegacyData data) gets invoked. Strangely the PerformCheck implementations are different depending on what is passed. I would like the PerformCheck(null) to invoke the PerformCheck(object data) implementation instead. How do I make this work?
CodePudding user response:
You can force the behavior by casting null to anything other than LegacyData.
var x = new Test();
x.PerformCheck((object)null);
public class Test
{
public void PerformCheck(LegacyData data) { Console.WriteLine("legacy"); }
public void PerformCheck(object data) { Console.WriteLine("other"); }
}
public class LegacyData {}
This outputs "other" as expected.
