7

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.

2
  • i am using visual studio 2015.. Dec 21, 2016 at 10:22
  • @bigyanshr - string? does not compile. string is already nullable and cannot be used as a type in Nullable<T>. Dec 21, 2016 at 20:25

2 Answers 2

15

Actually, your question is a little bit confusing because by the term nullable in the title, meantime you are looking for a method having default parameters/Optional parameters. which can be written 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");

2
  • It won't even compile :) The message will be: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' Dec 21, 2016 at 7:21
  • @MaksimSimkin : thank you For correcting me, I have updated the answer Dec 21, 2016 at 7:25
4

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.

2
  • Why would someone use this, and not the accepted answer? I see no use for this ugly solution.
    – Max
    Jul 12, 2018 at 14:05
  • One reason would be if you were supporting a legacy .net application as the accepted answer's syntax was not available until c# 4.
    – Chris
    Feb 1, 2019 at 0:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.