2

How to add an optional dictionary type parameter to any method.

I want to add a new optional parameter Dictionary to an existing method. I want to know if we could do this and if we could how could i default it to an empty dictionary of that type or null

2
  • 2
    You cannot provide a non-constant default-param. Thus you have to check for null within your method and assign an empty dictionary in that case as @Rahul mentioned Commented Oct 7, 2015 at 13:23
  • 1
    Adding an overload would be an option too. Commented Oct 7, 2015 at 13:28

2 Answers 2

7

You can try like this:

void myFun(Dictionary<string, string> param = null)
{
    if(param == null) 
    param = new Dictionary<string,string>();
}
Sign up to request clarification or add additional context in comments.

1 Comment

In newer versions, if you use <Nullable>enable</Nullable> the optional parameter needs to be defined as nullable Dictionary<string, string>? param = null
2
 void Foo(Dictionary<string, string> parameter){
        if(parameter == null) parameter = new Dictionary<string,string>();
    }

You could also make the parameter optional:

void Foo(Dictionary<string, string> parameter = null)
{
    if(parameter == null) parameter = new Dictionary<string,string>();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.