You can't, not directly. Default values for parameters must be compile-time constants.
You've got a couple of options.
The first is to use a sentinel default value, like null
:
public void findPath(string start, string end,
Dictionary<string, object[]> nodeInfo = null)
{
if (nodeInfo == null)
nodeInfo = new Dictionary<string, object[]>();
}
The second is to use method overloading:
public void findPath(string start, string end)
{
findPath(start, end, new Dictionary<string, object[]>();
}
public void findPath(string start, string end,
Dictionary<string, object[]> nodeInfo)
{
}
They need to be compile-time constants because they're baked into the places where the method is called. For example, if you used null
as a sentinel value and wrote this:
findPath("start", "end");
It gets compiled to this:
findPath("start", "end", null);
See the MSDN documentation on what is allowed as a default parameter value:
- a constant expression;
- an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
- an expression of the form default(ValType), where ValType is a value type.
Constant expressions:
Constants can be numbers, Boolean values, strings, or a null reference