5

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?

5
  • Can you not set the value in the constructor of your object? Commented Jul 30, 2015 at 7:03
  • You can't set default parameter value of a reference-type explicitly, try default(List<string>) instead. Commented Jul 30, 2015 at 7:05
  • yes.where is i set value?@BDH Commented Jul 30, 2015 at 7:08
  • @xtnd8 what did you mean? Commented Jul 30, 2015 at 7:09
  • @Mohadeseh_KH I mean List<string> Lst = default(List<string>) Commented Jul 30, 2015 at 7:13

4 Answers 4

13

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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
@Downvoter: Please explain?
2

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;
}

1 Comment

You can ommit the default-value for the seond method.
-1

Not quite sure what you want to achieve, but you can use ref to initialize the list if it is null.

void SetDefault(ref List<string> list)
{
    if(list == null)
    {
        list = new List<string>();
    }
}

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.