2

I have this method, this works as expected, it does not insert <string, value> if string is empty, however I have an issue where the string does't always exists. I want to avoid appending anything if string does not exists.

public static class StringBuilderExtension
{
    public static void AppendIfNotNull<TValue>(this StringBuilder sb, TValue value, string prefix)
        where TValue : class 
    {
        if (value != null)
        {
            sb.Append(prefix + value);
        }
    }
}

The issue is I am always passing the string key

sb.AppendIfNotNull(" width=\"", component.style.width + "\"");

This will appear as width="" as I physically appended the string. How can I stop this from happening.

I can stop it from appear if I wrap it around an if statement

if (item.width!= null)
{
    sb.AppendIfNotNull(" width=\"", item.width + "\"");
}

Object example. Property might exists in one object but might not on the next. e.g. Do not append color if it does not exists:

{
    'id': 'Test',
    'type': 'Text',
    'style': {
        'color': 'black'
        'textSize': '12'
    }
},
        {
    'id': 'Test',
    'type': 'Text',
    'style': {
        'textSize': '12'
    }
}
3
  • I am really wondering (after seeing the follow up questions), what it is you want to achieve, so what is the goal of adding this all to your string builder? Are you doing any kind of serialization at a later time? Commented May 1, 2019 at 12:46
  • What is string(key)? I don't see a key anywhere. It sounds like you just don't want to append the value if it's an empty string. You could just do var valueToAppend = value?.ToString(); and then if(!string.IsNullOrEmpty(valueToAppend)) sb,Append(prefix + valueToAppend); Commented May 1, 2019 at 12:48
  • Can you still add what your eventual output would be and what you would use it for? It almost sounds like using XElement might throw away all of your problems. Are you eventually generating XML? If that is the case, it might be interesting to look at other ways to handle that, than using a stringbuilder Commented May 1, 2019 at 14:20

2 Answers 2

2

You could simply change your add from a string prefix to a function that takes in TValue and returns you a string

public static class StringBuilderExtension
{
    public static void AppendIfNotNull<TValue>(this StringBuilder sb, TValue value, Func<TValue, string> transform)
        where TValue : class 
    {
        if (value != null)
        {
            sb.Append( transform( value ));
        }
    }
}

In this case, your transform will only be called when you are actually having a valid value

A sample way of using it could be

sb.AppendIfNotNull( token.style?.width, value => $" width=\"{value}\"" );

Where the ? implies a conditional null check (so if token.style is null, it would also be null)

I added a small sample to a dotnetfiddle where I did remove the generic type restriction ( because I was throwing numbers in ;) )

Sign up to request clarification or add additional context in comments.

10 Comments

I am appending it on a different method sb.AppendIfNotNull(" width=\"", item.width + "\""); With this new method do I simply call it sb.AppendIfNotNull(item.width) is this correct?
@Mask-dCodex I added how you should call it, I hope that helps?
Thanks Ice, just a few questions. The value i am obtaining is from a strongly typed object and if e.g. width doesnt exists in that object shouldnt it be token.style.width? and also I have tried to call that method but it is throwing There is no argument given that corresponds to the required formal parameter transform
@Mask-dCodex I did add a small sample to .net fiddle. Note that this doesn't support C# 6 features like conditional null check or string interpolation using $ prefix
Just a question. If Style was a list of would that imply that style? needs to be completely null in order not to add width? or is it only checking if width exists?
|
1

There is no way to do that with the current method signature, but you could separately pass the prefix, your value, and suffix:

public static void AppendIfNotNull<TValue>(this StringBuilder sb, TValue value, string prefix, string suffix)
    where TValue : class 
{
    if (value != null)
    {
        sb.Append(prefix + value + suffix);
    }
}

sb.AppendIfNotNull(item.width, " width=\"", "\"");

1 Comment

That really adds up after a while :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.