Charles Burns
Charles Burns

Reputation: 10602

How can a C# parameter with default value be null?

The code shown below shows a method Get which gets string search with default value: "".

Image showing null value for a parameter that has a default value

How can the value possibly be null when search has a non-null default value and is never changed?

Upvotes: 5

Views: 5788

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564333

How can the value possibly be null when search has a non-null default value and is never changed?

If you explicitly pass null to the method (or a variable which is null), the default is not used.

The default value is only used if you call the method without the parameter in place, in which case the compiler "fills in" the default value for you. If you call the method with something, including null or a object variable which is null, you will get a null value there.

Upvotes: 18

Related Questions