Home > Enterprise >  Overload function with null as argument
Overload function with null as argument

Time:03-17

I have a function that receives a string as argument:

public async Task<List<string>> GetNames(string name)
{
...
}

I want to overload that function to something like this:

public async Task<List<string>> GetNames(string name = null)
{
...
}

But in that case I am getting the following error:

"Type 'Nameservice' already defines a member called 'GetNames' with the same types".

How can I overload this method properly to be used when argument is null.

CodePudding user response:

How can I overload this method properly to be used when argument is null.

An overload aims to provide a method with the same name but a different parameter set. It is not meant to make an assertion about the values of the parameter. If you want to do that you would need to do it inside the method and in this case call another method

public async Task<List<string>> GetNames(string name)
{
    if(name is null)
    {
        return await GetNames();
    }
    else
    {
        // use "name"
    }
}


public async Task<List<string>> GetNames()
{
    // do something different
}

for clarification:

GetNames(string name = null)

this is not an overload, because the parameter set remains the same. This makes the parameter optional! so that it is not needed anymore at the calling site.

  • Related