Home > OS >  How to properly create a template string with conditions in C#?
How to properly create a template string with conditions in C#?

Time:07-07

I'm new to C# and have troubles translating my experience into it in certain things. I have two string variables in some class. They can be null or have a word stored in them. I need to create a result string out of them which depends on if they have values or not like in the example: Both variables have values: "string1 (string2)" Only first variable has value: "string1" Only second variable has value: "(string2)" Both are null: ""

So far I came up with this, but I doubt, that this is how it is supposed to be. Seems very rough

var str1 = SomeClass?.Str1   " " ?? string.Empty;
var str2 = "("   SomeClass?.Str2   ")" ?? string.Empty;
var result = $"{str1}{str2}";

Any suggestions? Thanks in advance

CodePudding user response:

You can use StringBuilder class to make the code more readable, an example:

using System.Text;

var sb = new StringBuilder();
if (!string.IsNullOrWhiteSpace(SomeClass?.Str1))
{
    sb.Append($"{SomeClass.Str1} ");
}
if (!string.IsNullOrWhiteSpace(SomeClass?.Str2))
{
    sb.Append($"({SomeClass.Str2})");
}

var result = sb.ToString();

Please note that StringBuilder is more efficient than string concatenation in .NET: https://docs.microsoft.com/en-us/troubleshoot/developer/visualstudio/csharp/language-compilers/string-concatenation

CodePudding user response:

non-null string "null" will result in a non-null string.

"a"   null == "a" // evaluates to true

This means that SomeClass?.Str1 " " and "(" SomeClass?.Str2 ")" will never be null.

Instead, do a null check on the member itself, without the surrounding text.

var result = "";

if (SomeClass?.Str1 is not null)
    result  = SomeClass.Str1;
if (SomeClass?.Str2 is not null)
    result  = " ("   SomeClass.Str1   ")";

You can use StringBuilder as well, but the point of this post is to point out the fallacies with your null checks.

CodePudding user response:

Here is an example of using an extension method that does the job. You can alter as required.

public static StringBuilder AddToString(this StringBuilder sb,string s)
{
if(!string.IsNullOrWhiteSpace(s))
sb.Append($"{s}");
return sb;
}

Usage

var sb = new StringBuilder();
sb.AddToString("a").AddToString("").AddToString("c");
Console.Write(sb.ToString());

//Result: ac //as there is a blank string.

CodePudding user response:

As suggested by Alik, I would recommend looking into StringBuilder.

You can do a lot of cool and advanced stuff like .AppendFormat("Foo {0}{1}{3}", 'B', 'a', 'r').

For more info/features have a look at: https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder

  •  Tags:  
  • c#
  • Related