Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

2 Answers

  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.

like image 81
maksymiuk Avatar answered Apr 16 '26 03:04

maksymiuk


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

like image 45
Hamid Pourjam Avatar answered Apr 16 '26 03:04

Hamid Pourjam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!