5

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?

3
  • 7
    If the parameter is present (but null) the default value won't be used.
    – Tim M.
    Mar 30, 2013 at 1:24
  • How are you calling the Get for MainView? Mar 30, 2013 at 1:25
  • Since this is Web API, you may want to check the raw request to see what values are being passed.
    – Tim M.
    Mar 30, 2013 at 1:28

1 Answer 1

18

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.

2
  • 1
    It might be worth mentioning that if the method is FooCorp.DLL and BarCorp.DLL is the caller, and FooCorp alters the method's default, calls from BarCorp.DLL will keep using the old value unless that assembly is also recompiled. Mar 30, 2013 at 1:33
  • 1
    Very true - as I said, the compiler "fills in" the default at compile time, which is a downside to default arguments in general. Mar 30, 2013 at 1:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.