-2

I am using concat to join 2 strings in my method, but I am facing a situation that If String A/B is null, instead of concating with String A/B, it should be empty. like this

var message = "ABC" + Null; 

So what I am looking for is that message = "" instead of ABC

How can I do that in C#

1
  • 1
    Well, don't use concatenation, because that's not how it works. Are you joining multiple values and you want the result to be null if any of the values is null? If so just add a check that all the values are not null first.
    – stuartd
    May 1, 2019 at 11:39

2 Answers 2

6

You can just use a simple if:

var message = string.Empty;

if (a != null && b != null)
{
    message = a + b;
}

Or, a one liner:

var message = (a == null || b == null) ? string.Empty : a + b;
0
0

You can simply do:

string ConcatIfNotNull(string a, string b)
{
    if (a == null || b == null)
        return "";
    else
        return a + b;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.