Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to differentiate between overloads when an argument is null

Tags:

c#

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)
    { ... }
}
like image 354
Andrew Avatar asked Jun 14 '13 11:06

Andrew


People also ask

How are overloaded methods distinguished from each other?

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.

What if we pass null as argument in Java?

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.

Can we pass NULL as a parameter?

You can pass NULL as a function parameter only if the specific parameter is a pointer.

Can you overload a function with the same number and types of arguments parameters but with a different return type?

No, you cannot overload a method based on different return type but same argument type and number in java.


1 Answers

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, "")
like image 118
Oded Avatar answered Nov 15 '22 05:11

Oded