I have a Dictionary<string, string>
as a method argument, and I was wondering if there is a way to make it default to an empty dictionary instead of null
. I prefer to always have an empty list/dictionary/IEnumerable instead of null
. I tried setting the parameter to:
Dictionary<string, string> dictionary = default(Dictionary<string,string>);
but that evaluates to null
.
Is there some way to make the default Dictionary empty?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With