Reputation: 47743
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 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?
Upvotes: 3
Views: 5075