Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group multiple if condition in C#?

Is there any better way to do this with fewer lines of code? Sometimes FirstName or SecondName or ThirdName values could be null - this code works but I want to improve the quality.

if (FirstName != null)
{
    txtEngageeName.Text = FirstName.ToString() ;
}
if (FirstName != null && SecondName != null)
{
    txtEngageeName.Text = FirstName.ToString() + SecondName.ToString();
}
if (FirstName != null && SecondName != null && ThirdName != null)
{
    txtEngageeName.Text = FirstName.ToString() + SecondName.ToString() + ThirdName.ToString();
}
like image 510
Sajeetharan Avatar asked Dec 09 '22 07:12

Sajeetharan


1 Answers

You can do simple (if you really don't want spaces between entities):

txtEngageeName.Text = string.Format("{0}{1}{2}", FirstName, SecondName, ThirdName);

Nulls will be formatted as empty string.

If you need spaces.

txtEngageeName.Text = string.Join(" ", new[] { FirstName, SecondName, ThirdName}.Where(s => s != null));
like image 53
Ulugbek Umirov Avatar answered Dec 11 '22 06:12

Ulugbek Umirov