Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable types as function parameter in C#

Tags:

c#

I saw this in a piece of code and was wondering if someone could help clarifying this for me.

public string MethodName(string str, int? x = null)
{
     if(x != null)
     {
          ....
     }
}

The second function parameter is where I'm confused:

int? x = null

I know about Nullable types, but I'm confused about the syntax here, I've never seen this before. Why is there a "= null" in the input parameter? The way that I'm reading it is it's setting x to null and it will never hit that first if, because x is always null.

like image 435
jlee Avatar asked Dec 22 '25 19:12

jlee


1 Answers

Here in the method signature x is an optional parameter, which means you can omit this argument if you do not want to change the parameter's default value. Consider the following calls to this function.

Call 1 : with two parameters

MethodName("AValue",10); // str = AValue and x=10

Call 2 : by skipping optional parameters

MethodName("AValue"); // str = AValue and x=null

Note :-

To define an optional parameter you should assign a default value to that parameter, so that if it is not specified in the function call the default value will be taken.

like image 145
sujith karivelil Avatar answered Dec 24 '25 07:12

sujith karivelil



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!