How to group multiple if conditions in C #?

Is there a better way to do this with fewer lines of code? Sometimes the values FirstNameor SecondNameor ThirdNamecan 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();
}
+4
source share
4 answers

You can make it simple (if you really don't need spaces between the objects):

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

Nulls will be formatted as an empty string.

If you need spaces.

txtEngageeName.Text = string.Join(" ", new[] { FirstName, SecondName, ThirdName}.Where(s => s != null));
+7
source

You can use the null-coalescing operator to get empty stringwhen the string nulland concatenation of the empty string have no effect.

txtEngageeName.Text =  (FirstName ?? "") + 
                       (SecondName ?? "") + 
                       (ThirdName ?? "");

trernary?: Operator, , .

string txtEngageeName = (FirstName == null ? "" : FirstName + " ") + 
                        (SecondName == null ? "" : SecondName + " ") + 
                        (ThirdName  ?? "");
+5

, Steve Fenton not SteveFenton, :

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

name = System.Text.RegularExpressions.Regex.Replace(name, @"\s+", " ");

// Show the result in the text box
txtEngageeName.Text = name;
+1
source

Use string.Format();

Like this:

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

Source: https://habr.com/ru/post/1542440/


All Articles