Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Is there an "Optional" keyword or alike in C#?

Tags:

c#

Is there a way in C# to mark a parameter as optional like VB.net's Optional keyword?

like image 957
Jack Avatar asked Nov 28 '22 02:11

Jack


1 Answers

There will be in C# 4.0

For now you can either overload your method, set a default value and call the other method. Or set it to nullable.

public void DoSomething(int a)
{
   int defaultValue = 1;
   DoSomething(a, defaultValue);
}

public void DoSomething(int a, int b)
{
    // Do something
}

or

public void DoSomething(int a, int? b)
{
   // Check for b.HasValue and do what you need to do
}
like image 181
Brandon Avatar answered Dec 19 '22 07:12

Brandon