开发者

Set StringBuilder before use?

Does a StringBuilder variable need to be initialized to lets say string.empty in case you don't end up appending anything in the end and need to return something?

    public static string ToSemiColonList<T>(this IEnumerable<T> list, Func<T, string> func)
    {
        StringBuilder sb = new StringBuilder();

        foreach (T item in 开发者_JS百科list)
        {
            if (sb.Length > 0)
                sb.Append(";");

            string elem = func(item);
            sb.Append(elem);
        }

        return sb.ToString();
    }

In this case it may never enter the foreach. So my guess is since every local variable in a method scope is set to no value in C#, to set it to an empty string since we need to give something back if this foreach is not hit.

Maybe it's better to check the stringbuilder length then if zero, return string.empty or am I going overboard (doing the same work twice) and it's fine like I have it?


Default initialization of a StringBuilder object gets set to string.Empty.

The default capacity is 16 - see here for a similar (but different) question on SO.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜