Make a Dictionary method argument default to an empty dictionary instead of null
Is there some way to make the default Dictionary empty?
Yes, use the constructor instead of default
:
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>();
}
An optional parameter must be a compile time constant, that's why you can't use new Dictionary<string,string>()
directly.
According to the question if you can change the behaviour of the default
keyword, no, you cannot return a different value. For reference types null
is the default value and will be returned.
C# language specs. §12.2:
The default value of a variable depends on the type of the variable and is determined as follows:
- For a variable of a value-type, the default value is the same as the value computed by the value-type’s default constructor (§11.1.2).
- For a variable of a reference-type, the default value is null.
Update: for what it's woth, you could use this extension (i wouldn't use it):
public static T EmptyIfNull<T>(this T coll)
where T : ICollection, new() // <-- Constrain to types with a default constructor and collections
{
if(coll == null)
return new T();
return coll;
}
Now you could use it in this way:
Dictionary<string, string> parameter = null;
Foo(parameter.EmptyIfNull()); // now an empty dictionary is passed
But the last thing another programmer wants to see is thousands of lines of code peppered with .EmptyIfNull()
everywhere just because the first guy was too lazy to use a constructor.