What does it mean when a C# function parameter contains `= null`?

719 Views Asked by At

I'm going through an MVC tutorial and see this line of code at the beginning of a function:

private void PopulateDepartmentsDropDownList(object selectedDepartment = null)

After testing it out, I can see that the function works, but I do not understand how the function parameter works. What does object selectedDepartment = null do?

I have done a general internet search and have not yet been able to locate an answer.

I guess my question really has two facets:

  1. What does the = null portion of the parameter do?
  2. Is it something that can be done but not necessarily should be done?
4

There are 4 best solutions below

1
On BEST ANSWER
  1. It means that that parameter will be null, unless you decide to pass something. So in other words, its optional.

  2. It can be done, and there is nothing wrong with it. Its pretty common practice.

0
On

This sets the argument to a default value (if not provided) and prevents a compile time error if the argument is not provided. See:

Setting the default value of a C# Optional Parameter

Basically this argument is now optional so you can call the function in either of these two ways:

PopulateDepartmentsDropDownList() //selectedDepartment will be set to null as it is not provided

OR

PopulateDepartmentsDropDownList(myObject) //selectedDepartment will become myObject
0
On

It means that you can call

PopulateDepartmentsDropDownList()

or

PopulateDepartmentsDropDownList("something")  

both because compiler will convert the first one to

PopulateDepartmentsDropDownList(null)

This feature is called Optional Arguments

I suggest you to read this blog post

1
On

the = null is the default value of the parameter, it is the functional equivalent as if you had

private void PopulateDepartmentsDropDownList()
{
    PopulateDepartmentsDropDownList(null);
}

private void PopulateDepartmentsDropDownList(object selectedDepartment)
{
     //Your code here.
}

So if you can call the function with no parameters PopulateDepartmentsDropDownList() it will call the 1 perameter version and pass in null.