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.. Commented 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>. Commented Dec 21, 2016 at 20:25

2 Answers 2

16

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");

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

2 Comments

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>'
@MaksimSimkin : thank you For correcting me, I have updated the answer
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 Comments

Why would someone use this, and not the accepted answer? I see no use for this ugly solution.
One reason would be if you were supporting a legacy .net application as the accepted answer's syntax was not available until c# 4.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.