Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set default parameter value for an action

How can I set default parameter value for an action when that parameter is dictionary type?

for example:

public void Test(Dictionary<int, bool> dic) {
    ...
}
like image 722
user667429 Avatar asked Dec 25 '22 19:12

user667429


2 Answers

You can't give it a default value the way you want to because it has to be a compile time constant value, but you can do something like this:

private static bool Test(Dictionary<string, string> par = null)
    {
        if(par == null) par = GetMyDefaultValue();
        // Custom logic here
        return false;
    }
like image 76
roqz Avatar answered Jan 05 '23 00:01

roqz


You could use null as special case, like in other answers, but if you still want to be able to call Test(null) and have different behaviour to calling Test(), then you must chain overload:

public void Test(Dictionary<int, bool> dic) {
  //optional, stops people calling Test(null) where you want them to call Test():
  if(dic == null) throw new ArgumentNullException("dic");
...
}

public void Test() {
   var defaultDic = new Dictionary<int, bool>();
   Test(defaultDic);
}
like image 45
weston Avatar answered Jan 05 '23 01:01

weston