user4864716
user4864716

Reputation:

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

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?

Upvotes: 3

Views: 902

Answers (4)

abagshaw
abagshaw

Reputation: 6582

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

Upvotes: 0

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

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

Upvotes: 2

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

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.

Upvotes: 1

maraaaaaaaa
maraaaaaaaa

Reputation: 8163

  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.

Upvotes: 5

Related Questions