This seems like something that I should have thought about before now, but it itn't. It also seems like there should be an existing way to do this.
The problem: Say I have a class with a couple of constructors
public class ModuleAction
{
public ModuleAction(string url, string caption)
{ ... }
public ModuleAction(string url, ModuleAction action)
{ ... }
}
And then elsewhere, I make a call to one of those constructors, but the second argument is null, it does not know which constructor to use
ModuleAction action = new ModuleAction("http://google.co.uk", null);
Is there any way of doing this? My current solution is to add an unused argument to one of the constructors, but that doesn't seem right.
My solution: (not pretty)
public class ModuleAction
{
public ModuleAction(string url, string caption, bool unused)
{ ... }
public ModuleAction(string url, ModuleAction action)
{ ... }
}
Overloaded methods are differentiated based on the number and type of parameter passed as arguments to the methods. If we try to define more than one method with the same name and the same number of arguments then the compiler will throw an error.
When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn't happen unless we intentionally pass null value.
You can pass NULL as a function parameter only if the specific parameter is a pointer.
No, you cannot overload a method based on different return type but same argument type and number in java.
There are several options here.
The simple, direct solution is to cast the null
to they type of the argument in the overload you wish to use:
ModuleAction action = new ModuleAction("http://google.co.uk", (string)null);
A better option would be to use a new constructor that has a single parameter and to chain it, using defaults:
public ModuleAction(string url) : this(url, "")
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