Search code examples
c#.netstringconcatenation

Concatenate two strings and get null if both are null


I am looking for a solution to concatenate two string values and get null as a result if both are null. None of string1 + string2, string.Concat(string1, string2), string.Join(string1, string2) work. Research shows that is due to the fact, that these methods internally treat null as empty string.

How to solve this?


Solution

  • Something like this?

    public class StringTest
    {
        public string CustomConcat(string one, string two) => 
            one == null && two == null 
                ? null 
                : string.Concat(one, two);
    
        [Test]
        public void ConcatTest()
        {
            Assert.IsNull(CustomConcat(null, null));
            Assert.AreEqual("one", CustomConcat("one", null));
            Assert.AreEqual("two", CustomConcat(null, "two"));
            Assert.AreEqual("onetwo", CustomConcat("one", "two"));
    
            // finally, a test for (a + b) ?? (c + d)
            Assert.AreEqual("threefour", CustomConcat(null, null) ?? CustomConcat("three", "four"));
        }
    }