Turo
Turo

Reputation: 1607

Optional Arguments or Named Arguments initialized to null? C#

I came across an example similar to this:

public Dictionary<string, object> generate(
  string elementId,
  Dictionary<string, object> additionalAttributes = null)
{
.... method body
}

Why would the dictionary passed as parameter be initiated to null? I haven't seen such construct. Does it have to do something with an optional parameter?

Upvotes: 0

Views: 1851

Answers (4)

Yes it saves time if you are using Function Overloading For example this can be avoided

Void Main()
        {
          fun1(11);
          fun1(12,13);
        }

    public fun1(int i )
    {
    Print(i);
    }

    public fun1(int i ,int j)
    {
    Print(i+j);
    }

This can be avoided by Code below and it also saves time and space

Void Main()
{
fun1(12);
}

public fun1(int i ,int j = NULL)
{
if(j==NULL)
  Print(i);
else
Print(i+j);
}

Upvotes: 0

MikeT
MikeT

Reputation: 5500

Optional parameter such as the one you use in your example can only be set to constant values, this means that you can't use any reference values, which is what Dictionary is, as such null is the only allowed value you can initialise an optional variable of type Dictionary to, if the method was using a value type like int or string then a value could be initialised for the optional parameter otherwise it has to be null

Upvotes: 0

Khalil Khalaf
Khalil Khalaf

Reputation: 9397

I use that to save time writing functions overloading. For example, instead of overloading two functions:

void SameFunctionName(Parameter1){ .. }
void SameFunctionName(Parameter1, Parameter2){ .. }
// maybe additional function body with three parameters .. etc

I just write one using this case:

void MyFunction(Parameter1, Parameter2 = null){ .. }

So, a small if statement inside my function would check if Parameter2 is null or not, to then make decisions. All in one function body.

and the function call for this case would work in both cases:

MyFunction(Parameter1); // This is a valid syntax
MyFunction(Parameter1, Parameter2); // This is a valid syntax

Upvotes: 1

Dan Forbes
Dan Forbes

Reputation: 2824

I can't speak to your first question, but the answer to your second question is yes. This is an optional parameter. C# only allows optional reference-type parameters to take a default value of null, except for string, which can take any constant string value, I believe.

Ref: MSDN

Upvotes: 3

Related Questions