Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the WPF Presentation library wrap strings in StringBuilder.ToString()?

Tags:

The code found in the PresentationCore.dll (.NET4 WPF) by ILSpy:

// MS.Internal.PresentationCore.BindUriHelper internal static string UriToString(Uri uri) {     if (uri == null)     {         throw new ArgumentNullException("uri");     }      return new StringBuilder(uri.GetComponents(uri.IsAbsoluteUri ? UriComponents.AbsoluteUri : UriComponents.SerializationInfoString, UriFormat.SafeUnescaped), 2083).ToString(); } 

The return type of uri.GetComponents is string, why didn't the method just return the string value instead of wrapping it in a StringBuilder(string).ToString(); Is this by design? What would be the reason for doing this in a general sense? Would it reduce allocations or improve Garbage Collection or used for thread safety?

like image 873
Aimeast Avatar asked Jan 31 '14 11:01

Aimeast


1 Answers

Only thing I can think of is that if the first parameter being passed into the stringBuilder is null, then the stringbuilder will return string.empty rather than null (see http://msdn.microsoft.com/en-us/library/zb91weab(v=vs.100).aspx)

A string is nullable though... so why bother?!

Just doing a check and returning an empty string yourself would be a lot more efficient than newing up a stringBuilder instance.

The second parameter is just a suggested size that the stringbuilder should be initialized to...

Comments on the OP's question are right, it appears to be overkill.

like image 58
Jay Avatar answered Oct 02 '22 12:10

Jay