From 76048c739addb3da99ce12e886ded090753b5579 Mon Sep 17 00:00:00 2001 From: James Ko Date: Thu, 25 Aug 2016 18:01:02 -0400 Subject: [PATCH] Avoid unnecessary indirection in char.ToString (#6903) Avoid unnecessary indirection in char.ToString --- src/mscorlib/src/System/Char.cs | 5 +---- src/mscorlib/src/System/String.cs | 13 ++++++++++++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/mscorlib/src/System/Char.cs b/src/mscorlib/src/System/Char.cs index c7fd4b3..ff936c6 100644 --- a/src/mscorlib/src/System/Char.cs +++ b/src/mscorlib/src/System/Char.cs @@ -163,10 +163,7 @@ namespace System { ==============================================================================*/ // Provides a string representation of a character. [Pure] - public static String ToString(char c) { - Contract.Ensures(Contract.Result() != null); - return new String(c, 1); - } + public static string ToString(char c) => string.CreateFromChar(c); public static char Parse(String s) { if (s==null) { diff --git a/src/mscorlib/src/System/String.cs b/src/mscorlib/src/System/String.cs index 841af22..2956c42 100644 --- a/src/mscorlib/src/System/String.cs +++ b/src/mscorlib/src/System/String.cs @@ -25,6 +25,7 @@ namespace System { using System.Runtime.Versioning; using Microsoft.Win32; using System.Diagnostics.Contracts; + using System.Security; // // For Information on these methods, please see COMString.cpp @@ -1488,7 +1489,6 @@ namespace System { return TrimHelper(trimChars,TrimTail); } - // Creates a new string with the characters copied in from ptr. If // ptr is null, a 0-length string (like String.Empty) is returned. // @@ -1567,6 +1567,17 @@ namespace System { return s; } + + // This is only intended to be used by char.ToString. + // It is necessary to put the code in this class instead of Char, since m_firstChar is a private member. + // Making m_firstChar internal would be dangerous since it would make it much easier to break String's immutability. + [SecuritySafeCritical] + internal static string CreateFromChar(char c) + { + string result = FastAllocateString(1); + result.m_firstChar = c; + return result; + } [System.Security.SecuritySafeCritical] // auto-generated unsafe internal int GetBytesFromEncoding(byte* pbNativeBuffer, int cbNativeBuffer,Encoding encoding) -- 2.7.4