Set default value for parameter of List<string> type in function

23,050

Solution 1

Currently it's not possible in C# to initialize parameters with new objects or classes.

You can leave default value as null and in your method create your class instance:

private bool test(List<string> Lst = null)
{
    if(Lst == null)
    {
       Lst = new List<string> { "ID" };
    }
    return false;
}

In C# 8 we could shorten this kind of expressions with the new null conditional operator:

private bool test(List<string> Lst = null)
{
    Lst ??= new List<string> { "ID" };
    return false;
}

Solution 2

You can set the default to null and then set this to your desired default in the first line

private bool test(List<string> Lst = null)
{
    List<string> tempList; // give me a name
    if(Lst == null)
         tempList = new List<string>() { "ID" };
    else 
         tempList = Lst;

    return false;
}

Now you can use tempList in your desired way

Solution 3

This is not possible. See the MSDN docs for allowed values.

A possible alternative is to use overrides and/or a default value of null instead. Use either:

// Override
private bool test()
{
    return test(new List<string>() { "ID" });
}

// default of null
private bool test(List<string> Lst = null)
{
    if (Lst == null) {
        Lst = new List<string>() { "ID" };
    }

    return false;
}
Share:
23,050
Mohadeseh_KH
Author by

Mohadeseh_KH

Updated on October 06, 2021

Comments

  • Mohadeseh_KH
    Mohadeseh_KH over 2 years

    I write this code :

     private bool test(List<string> Lst = new List<string>() { "ID" })
        {
    
            return false;
        }
    

    i want to set default value for "Lst" but has an error from "new" key word. any idea?

  • Sayse
    Sayse almost 9 years
    Note: I'm not a fan of this since it is unclear to the developer that this will actually use this fake list rather than null
  • MakePeaceGreatAgain
    MakePeaceGreatAgain almost 9 years
    You can ommit the default-value for the seond method.
  • Sayse
    Sayse almost 9 years
    @Downvoter: Please explain?
  • Lorenzo
    Lorenzo about 3 years
    He might actually need the list to be null in specific use-cases, which i also guess is why this answer was downvoted. At my work specifically, we check for null to differentiate when a use gave an input or not. If you automatically initialize the list magically somewhere you would break the kind of logic i'm talking about.