I am trying to pass optional parameter to method and having hard times understanding why it doesn't work. As most popular answer here (How can you use optional parameters in C#?) says public void SomeMethod(int a, int b = 0)
. So I have tried the same below.
Can I get rid of else
statement here? I mean can I use parameter that is otherwise =""
if not something else = optional? If it exists, method will get it, if not then skip it?
Here is code with else statement that works (https://dotnetfiddle.net/sy5FW5):
using System;
public class Program
{
public static void Main()
{
int MyNumber = 6;
string StringOne;
string StringTwo;
if (MyNumber != 5)
{
StringOne = "Number is not 5";
StringTwo = "True that!";
}
else
{
StringOne = "";
StringTwo = "";
}
CheckNumber(StringOne, StringTwo);
}
public static void CheckNumber(string StringOne, string StringTwo)
{
Console.WriteLine(StringOne + "\n" + StringTwo);
}
}
Above code is what I need and it is working fine. My question is more like is there any better way?
Here is what I was thinking of, but it does not work:
using System;
public class Program
{
public static void Main()
{
int MyNumber = 6;
string StringOne;
string StringTwo;
if (MyNumber != 5)
{
StringOne = "Number is not 5";
StringTwo = "True that!";
}
CheckNumber(StringOne, StringTwo);
}
public static void CheckNumber(string StringOne = "", string StringTwo = "")
{
Console.WriteLine(StringOne + "\n" + StringTwo);
}
}
Variables are not assigned in: CheckNumber(StringOne, StringTwo);
I was thinking that I can make parameters optional by using string StringOne = ""
but it does not seem to be the solution?