-1

Hey i can't seem to find the answer to this question answered in a way that makes complete sense to me.

when declaring nullable arguments in c#, what is the difference between declaring a argument with a question mark like this:

public method(int? variable):

and with an assignment like this:

public method(int variable = null):
Ask Sejsbo
  • 93
  • 1
  • 8
  • 1
    you can't do the second case without making `int` nullable. – Daniel A. White Oct 06 '19 at 19:00
  • well, i should have used a reference type instead of int, my mistake. i think what i dont understand is what the difference is between nullable and optional – Ask Sejsbo Oct 06 '19 at 19:10
  • Well the first one will compile. If you want to make the parameter `variable` optional with a default value of `null`, then you'd say `public method(int? variable = null):` – Flydog57 Oct 06 '19 at 19:10
  • thanks flydog! but if i want it to be null at default, why do i need to add the question mark? it seems like it should be enough with just the assignment? – Ask Sejsbo Oct 06 '19 at 19:15
  • Value types (like int, other numeric types, enums and anything defined as a `struct`) are not normally nullable. To add `null` to the range of a value type variable, declare it as nullable (either `int?` or `Nullable`). If you add a default expression to a parameter declaration for a method (like`(int? variable = null)`), then you are declaring the parameter to be optional. If the caller doesn't specify a value for that parameter at the call site, the parameter is considered to have its default value in the body of the method – Flydog57 Oct 06 '19 at 19:19
  • ahhhh, I see. So i wouldnt need to use the question mark for a reference type? like string – Ask Sejsbo Oct 06 '19 at 19:23
  • Variables typed as reference types are nullable all on their own. Every variable has a `default` value (for example, the default for `int`s is zero). The default value for variables that are reference type is `null` (which signals that the variable refers to nothing). Value types always have a value associated with them. Nullable value types simple accept `null` as one of those values. The latest C# has *nullable reference types* which is a misnomer kind of. If you enable that feature, the ref type variables cannot be null unless they are described as accepting null as a value. – Flydog57 Oct 06 '19 at 20:03

1 Answers1

0

The first makes a required nullable int argument named variable. The second won't even compile.

If you were to do

public method(int? variable = null)

Then you could call method as method(), not passing a value for variable and null will be inserted by the compiler call which is the default value provided in the parameter.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445