Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a Dictionary method argument default to an empty dictionary instead of null

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?

like image 225
Nostradamnit Avatar asked Nov 18 '14 11:11

Nostradamnit


1 Answers

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.

like image 152
Tim Schmelter Avatar answered Oct 29 '22 17:10

Tim Schmelter