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.
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.
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.)
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.
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With