-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):
7
  • 1
    you can't do the second case without making int nullable. Commented Oct 6, 2019 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 Commented Oct 6, 2019 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): Commented Oct 6, 2019 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? Commented Oct 6, 2019 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<int>). 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 Commented Oct 6, 2019 at 19:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh yes, I should have used a reference type in my example. My mistake.
Okay, I'm lost. I'm not saying I'd encourage the use of int?, but neither is this answer, necessarily. Why the downvotes?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.