Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle nullable string as a function parameter

I have function with parameters as given below.

public void myfunction(int a, string b){}

Can we call this function by passing only first parameter and second parameter is optional(nullable string)?

myfunction(5);

If yes then how.

like image 607
Neha Thakur Avatar asked Dec 21 '16 07:12

Neha Thakur


People also ask

How do you pass a parameter as null?

You can pass NULL as a function parameter only if the specific parameter is a pointer. The only practical way is with a pointer for a parameter. However, you can also use a void type for parameters, and then check for null, if not check and cast into ordinary or required type.

Can string be nullable?

In C# 8.0, strings are known as a nullable “string!”, and so the AllowNull annotation allows setting it to null, even though the string that we return isn't null (for example, we do a comparison check and set it to a default value if null.)

What is a nullable parameter?

Use two commas (,,) to give a parameter variable a null value when it is followed by other non-null parameters. After the last non-null parameter, all remaining parameter variables up to &31 are automatically given null values. Null parameters are useful when a value is not required.


2 Answers

Actually your question is little bit confusing by the term nullable in the title, mean time you are looking for a method having default parameters/Optional parameters. which can be written as like the following:

public void myfunction(int a, string b = ""){}

So that you can call like this myfunction(5); or like myfunction(5,null); or even this: myfunction(5,"Something");

like image 128
sujith karivelil Avatar answered Oct 21 '22 03:10

sujith karivelil


just overload the function as follows:

public void myfunction(int a, string b)
{
   //do stuff
}

public void myfunction(int a)
{
  myfunction(a,string.empty);
}

then call

myFuntion(5);

Note: It's best practice to use string.empty instead of null so have shown that in my example.

like image 31
Chris Avatar answered Oct 21 '22 02:10

Chris