diff --git a/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.ParseMapModules.cs b/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.ParseMapModules.cs index eeb472a19e5..8be9f32cbed 100644 --- a/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.ParseMapModules.cs +++ b/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.ParseMapModules.cs @@ -15,8 +15,7 @@ internal static partial class Interop { private const string MapsFileName = "/maps"; - private static string GetMapsFilePathForProcess(int pid) => - RootPath + pid.ToString(CultureInfo.InvariantCulture) + MapsFileName; + private static string GetMapsFilePathForProcess(int pid) => string.Create(null, stackalloc char[256], $"{RootPath}{(uint)pid}{MapsFileName}"); internal static ProcessModuleCollection? ParseMapsModules(int pid) { diff --git a/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.TryReadStatusFile.cs b/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.TryReadStatusFile.cs index 5dc24477bee..22b06128926 100644 --- a/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.TryReadStatusFile.cs +++ b/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.TryReadStatusFile.cs @@ -30,10 +30,7 @@ internal static partial class Interop internal ulong VmPeak; } - internal static string GetStatusFilePathForProcess(int pid) - { - return RootPath + pid.ToString(CultureInfo.InvariantCulture) + StatusFileName; - } + internal static string GetStatusFilePathForProcess(int pid) => string.Create(null, stackalloc char[256], $"{RootPath}{(uint)pid}{StatusFileName}"); internal static bool TryReadStatusFile(int pid, out ParsedStatus result) { diff --git a/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.cs b/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.cs index 0ca179b736e..a85ec0a5f4f 100644 --- a/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.cs +++ b/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.cs @@ -76,41 +76,17 @@ internal static partial class Interop //internal long cguest_time; } - internal static string GetExeFilePathForProcess(int pid) - { - return RootPath + pid.ToString(CultureInfo.InvariantCulture) + ExeFileName; - } + internal static string GetExeFilePathForProcess(int pid) => string.Create(null, stackalloc char[256], $"{RootPath}{(uint)pid}{ExeFileName}"); - internal static string GetCmdLinePathForProcess(int pid) - { - return RootPath + pid.ToString(CultureInfo.InvariantCulture) + CmdLineFileName; - } + internal static string GetCmdLinePathForProcess(int pid) => string.Create(null, stackalloc char[256], $"{RootPath}{(uint)pid}{CmdLineFileName}"); - internal static string GetStatFilePathForProcess(int pid) - { - return RootPath + pid.ToString(CultureInfo.InvariantCulture) + StatFileName; - } + internal static string GetStatFilePathForProcess(int pid) => string.Create(null, stackalloc char[256], $"{RootPath}{(uint)pid}{StatFileName}"); - internal static string GetTaskDirectoryPathForProcess(int pid) - { - return RootPath + pid.ToString(CultureInfo.InvariantCulture) + TaskDirectoryName; - } + internal static string GetTaskDirectoryPathForProcess(int pid) => string.Create(null, stackalloc char[256], $"{RootPath}{(uint)pid}{TaskDirectoryName}"); - internal static string GetFileDescriptorDirectoryPathForProcess(int pid) - { - return RootPath + pid.ToString(CultureInfo.InvariantCulture) + FileDescriptorDirectoryName; - } + internal static string GetFileDescriptorDirectoryPathForProcess(int pid) => string.Create(null, stackalloc char[256], $"{RootPath}{(uint)pid}{FileDescriptorDirectoryName}"); - private static string GetStatFilePathForThread(int pid, int tid) - { - // Perf note: Calling GetTaskDirectoryPathForProcess will allocate a string, - // which we then use in another Concat call to produce another string. The straightforward alternative, - // though, since we have five input strings, is to use the string.Concat overload that takes a params array. - // This results in allocating not only the params array but also a defensive copy inside of Concat, - // which means allocating two five-element arrays. This two-string approach will result not only in fewer - // allocations, but also typically in less memory allocated, and it's a bit more maintainable. - return GetTaskDirectoryPathForProcess(pid) + tid.ToString(CultureInfo.InvariantCulture) + StatFileName; - } + private static string GetStatFilePathForThread(int pid, int tid) => string.Create(null, stackalloc char[256], $"{RootPath}{(uint)pid}{TaskDirectoryName}{(uint)tid}{StatFileName}"); internal static bool TryReadStatFile(int pid, out ParsedStat result) { diff --git a/src/libraries/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs b/src/libraries/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs index a2c6255541e..f3344792900 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Net.Security.Native/Interop.GssBuffer.cs @@ -19,7 +19,7 @@ internal static partial class Interop internal int Copy(byte[] destination, int offset) { Debug.Assert(destination != null, "target destination cannot be null"); - Debug.Assert((offset >= 0 && offset < destination.Length) || destination.Length == 0, "invalid offset " + offset); + Debug.Assert((offset >= 0 && offset < destination.Length) || destination.Length == 0, $"invalid offset {offset}"); if (_data == IntPtr.Zero || _length == 0) { diff --git a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs index 604ac8b4c79..47a9312266e 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs @@ -295,7 +295,7 @@ internal static partial class Interop { #if DEBUG ulong assertNoError = Crypto.ErrPeekError(); - Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error."); + Debug.Assert(assertNoError == 0, $"OpenSsl error queue is not empty, run: 'openssl errstr {assertNoError:X}' for original error."); #endif errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; @@ -349,7 +349,7 @@ internal static partial class Interop { #if DEBUG ulong assertNoError = Crypto.ErrPeekError(); - Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error."); + Debug.Assert(assertNoError == 0, $"OpenSsl error queue is not empty, run: 'openssl errstr {assertNoError:X}' for original error."); #endif errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SecurityPackageInfoClass.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SecurityPackageInfoClass.cs index ea65be9600e..ada41ba189f 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SecurityPackageInfoClass.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SecurityPackageInfoClass.cs @@ -59,14 +59,7 @@ namespace System.Net if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, this.ToString()); } - public override string ToString() - { - return "Capabilities:" + string.Format(CultureInfo.InvariantCulture, "0x{0:x}", Capabilities) - + " Version:" + Version.ToString(NumberFormatInfo.InvariantInfo) - + " RPCID:" + RPCID.ToString(NumberFormatInfo.InvariantInfo) - + " MaxToken:" + MaxToken.ToString(NumberFormatInfo.InvariantInfo) - + " Name:" + ((Name == null) ? "(null)" : Name) - + " Comment:" + ((Comment == null) ? "(null)" : Comment); - } + public override string ToString() => + $"Capabilities:0x{Capabilities:x} Version:{Version} RPCID:{RPCID} MaxToken:{MaxToken} Name:{Name ?? "(null)"} Comment: {Comment ?? "(null)"}"; } } diff --git a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs index 281691f7907..4ddf9950f5c 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs @@ -327,7 +327,7 @@ namespace System.Runtime.Serialization string returnType = _baseType; return _needsFixup && TypeArguments.Count > 0 ? - returnType + '`' + TypeArguments.Count.ToString(CultureInfo.InvariantCulture) : + $"{returnType}`{(uint)TypeArguments.Count}" : returnType; } set diff --git a/src/libraries/Common/src/System/Composition/Diagnostics/DebuggerTraceWriter.cs b/src/libraries/Common/src/System/Composition/Diagnostics/DebuggerTraceWriter.cs index 8630d366a86..f716210055d 100644 --- a/src/libraries/Common/src/System/Composition/Diagnostics/DebuggerTraceWriter.cs +++ b/src/libraries/Common/src/System/Composition/Diagnostics/DebuggerTraceWriter.cs @@ -57,8 +57,7 @@ namespace System.Composition.Diagnostics StringBuilder messageBuilder = new StringBuilder(); // Format taken from TraceListener.TraceEvent in .NET Framework - messageBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0} {1}: {2} : ", - s_sourceName, eventType.ToString(), (int)traceId); + messageBuilder.Append($"{s_sourceName} {eventType}: {(int)traceId} : "); if (arguments == null) { diff --git a/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs b/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs index 80a092104ae..54df9fa7798 100644 --- a/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs +++ b/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs @@ -525,11 +525,11 @@ namespace System.Data.Common } } } - Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <" + msg1 + "> <" + msg2 + ">"); + Debug.Assert(isEquivalent, $"ParseInternal code vs regex message mismatch: <{msg1}> <{msg2}>"); } else { - Debug.Fail("ParseInternal code vs regex throw mismatch " + f.Message); + Debug.Fail($"ParseInternal code vs regex throw mismatch {f.Message}"); } e = null; } diff --git a/src/libraries/Common/src/System/Drawing/ColorTranslator.cs b/src/libraries/Common/src/System/Drawing/ColorTranslator.cs index d1caed09be2..b8fc7866abe 100644 --- a/src/libraries/Common/src/System/Drawing/ColorTranslator.cs +++ b/src/libraries/Common/src/System/Drawing/ColorTranslator.cs @@ -386,9 +386,7 @@ namespace System.Drawing } else { - colorString = "#" + c.R.ToString("X2", null) + - c.G.ToString("X2", null) + - c.B.ToString("X2", null); + colorString = $"#{c.R:X2}{c.G:X2}{c.B:X2}"; } return colorString; diff --git a/src/libraries/Common/src/System/IO/RowConfigReader.cs b/src/libraries/Common/src/System/IO/RowConfigReader.cs index a6bfd96daf4..571aa9afd9e 100644 --- a/src/libraries/Common/src/System/IO/RowConfigReader.cs +++ b/src/libraries/Common/src/System/IO/RowConfigReader.cs @@ -132,7 +132,7 @@ namespace System.IO } // Check If the match is at the beginning of the string, or is preceded by a newline. else if (keyIndex == 0 - || (keyIndex >= Environment.NewLine.Length && _buffer.Substring(keyIndex - Environment.NewLine.Length, Environment.NewLine.Length) == Environment.NewLine)) + || (keyIndex >= Environment.NewLine.Length && _buffer.AsSpan(keyIndex - Environment.NewLine.Length, Environment.NewLine.Length).SequenceEqual(Environment.NewLine))) { // Check if the match is followed by whitespace, meaning it is not part of a larger word. if (HasFollowingWhitespace(keyIndex, key.Length)) diff --git a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs index 4e4e0c672b4..a145951254a 100644 --- a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs +++ b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs @@ -212,7 +212,7 @@ namespace System.Net.Security // throw if error if (errorCode != 0) { - NetEventSource.Info($"VerifySignature threw error: {errorCode.ToString("x", NumberFormatInfo.InvariantInfo)}"); + NetEventSource.Info($"VerifySignature threw error: {errorCode:x}"); throw new Win32Exception(errorCode); } @@ -256,7 +256,7 @@ namespace System.Net.Security // throw if error if (errorCode != 0) { - NetEventSource.Info($"MakeSignature threw error: {errorCode.ToString("x", NumberFormatInfo.InvariantInfo)}"); + NetEventSource.Info($"MakeSignature threw error: {errorCode:x}"); throw new Win32Exception(errorCode); } diff --git a/src/libraries/Common/tests/StaticTestGenerator/Program.cs b/src/libraries/Common/tests/StaticTestGenerator/Program.cs index 1c25d5ccd4c..2274463eba9 100644 --- a/src/libraries/Common/tests/StaticTestGenerator/Program.cs +++ b/src/libraries/Common/tests/StaticTestGenerator/Program.cs @@ -710,12 +710,12 @@ namespace StaticTestGenerator if (literal is IntPtr ptr) { - return $"new IntPtr(0x{((long)ptr).ToString("X")})"; + return $"new IntPtr(0x{(long)ptr:X})"; } if (literal is UIntPtr uptr) { - return $"new UIntPtr(0x{((ulong)uptr).ToString("X")})"; + return $"new UIntPtr(0x{(ulong)uptr:X})"; } string? result = null; @@ -732,34 +732,34 @@ namespace StaticTestGenerator result = ((bool)literal).ToString().ToLowerInvariant(); break; case TypeCode.Char: - result = $"'\\u{((int)(char)literal).ToString("X4")}'"; + result = $"'\\u{(int)(char)literal:X4}'"; break; case TypeCode.SByte: - result = $"(sbyte)({literal.ToString()})"; + result = $"(sbyte)({literal})"; break; case TypeCode.Byte: - result = $"(byte){literal.ToString()}"; + result = $"(byte){literal}"; break; case TypeCode.Int16: - result = $"(short)({literal.ToString()})"; + result = $"(short)({literal})"; break; case TypeCode.UInt16: - result = $"(ushort){literal.ToString()}"; + result = $"(ushort){literal}"; break; case TypeCode.Int32: - result = $"({literal.ToString()})"; + result = $"({literal})"; break; case TypeCode.UInt32: - result = $"{literal.ToString()}U"; + result = $"{literal}U"; break; case TypeCode.Int64: - result = $"({literal.ToString()}L)"; + result = $"({literal}L)"; break; case TypeCode.UInt64: - result = $"{literal.ToString()}UL"; + result = $"{literal}UL"; break; case TypeCode.Decimal: - result = $"({literal.ToString()}M)"; + result = $"({literal}M)"; break; case TypeCode.Single: result = diff --git a/src/libraries/Common/tests/System/Net/Http/HttpProtocolTests.cs b/src/libraries/Common/tests/System/Net/Http/HttpProtocolTests.cs index ec7bb197e81..b90cffafeab 100644 --- a/src/libraries/Common/tests/System/Net/Http/HttpProtocolTests.cs +++ b/src/libraries/Common/tests/System/Net/Http/HttpProtocolTests.cs @@ -447,7 +447,7 @@ namespace System.Net.Http.Functional.Tests { int bytesRemaining = expectedData.Length - bytesSent; int bytesToSend = rand.Next(1, Math.Min(bytesRemaining, maxChunkSize + 1)); - await connection.WriteStringAsync(bytesToSend.ToString("X") + lineEnding); + await connection.WriteStringAsync($"{bytesToSend:X}{lineEnding}"); await connection.Stream.WriteAsync(new Memory(expectedData, bytesSent, bytesToSend)); await connection.WriteStringAsync(lineEnding); bytesSent += bytesToSend; diff --git a/src/libraries/Common/tests/System/Security/Cryptography/ByteUtils.cs b/src/libraries/Common/tests/System/Security/Cryptography/ByteUtils.cs index 997b09af0cb..8a1a95bb098 100644 --- a/src/libraries/Common/tests/System/Security/Cryptography/ByteUtils.cs +++ b/src/libraries/Common/tests/System/Security/Cryptography/ByteUtils.cs @@ -55,7 +55,7 @@ namespace Test.Cryptography for (int i = 0; i < bytes.Length; i++) { - builder.Append(bytes[i].ToString("X2")); + builder.Append($"{bytes[i]:X2}"); } return builder.ToString(); diff --git a/src/libraries/Common/tests/System/Xml/XmlCoreTest/ManagedNodeWriter.cs b/src/libraries/Common/tests/System/Xml/XmlCoreTest/ManagedNodeWriter.cs index a96b25090b7..d51c5e3cf87 100644 --- a/src/libraries/Common/tests/System/Xml/XmlCoreTest/ManagedNodeWriter.cs +++ b/src/libraries/Common/tests/System/Xml/XmlCoreTest/ManagedNodeWriter.cs @@ -109,14 +109,14 @@ namespace XmlCoreTest.Common if (pubid == null) { if (sysid != null) - dt.Append(" SYSTEM " + sysid); + dt.Append($" SYSTEM {sysid}"); } else { - dt.Append(" PUBLIC " + pubid); + dt.Append($" PUBLIC {pubid}"); if (sysid != null) { - dt.Append(" " + sysid); + dt.Append($" {sysid}"); } } @@ -298,7 +298,7 @@ namespace XmlCoreTest.Common /// public void PutCData() { - _q.Append(""); + _q.Append($""); } /// @@ -306,7 +306,7 @@ namespace XmlCoreTest.Common /// public void PutPI() { - _q.Append(""); + _q.Append($""); } /// @@ -314,7 +314,7 @@ namespace XmlCoreTest.Common /// public void PutComment() { - _q.Append(""); + _q.Append($""); } /// diff --git a/src/libraries/Common/tests/System/Xml/XmlDiff/XmlDiffDocument.cs b/src/libraries/Common/tests/System/Xml/XmlDiff/XmlDiffDocument.cs index c765bf4a589..23cfda1c710 100644 --- a/src/libraries/Common/tests/System/Xml/XmlDiff/XmlDiffDocument.cs +++ b/src/libraries/Common/tests/System/Xml/XmlDiff/XmlDiffDocument.cs @@ -1594,7 +1594,7 @@ namespace System.Xml.XmlDiff w.WriteString(Value); break; default: - Debug.Assert(false, "Wrong type for text-like node : " + this._nodetype.ToString()); + Debug.Assert(false, $"Wrong type for text-like node : {this._nodetype}"); break; } } diff --git a/src/libraries/Common/tests/TestUtilities.Unicode/System/Text/Unicode/ParsedUnicodeData.cs b/src/libraries/Common/tests/TestUtilities.Unicode/System/Text/Unicode/ParsedUnicodeData.cs index 6496568c75b..c7155243400 100644 --- a/src/libraries/Common/tests/TestUtilities.Unicode/System/Text/Unicode/ParsedUnicodeData.cs +++ b/src/libraries/Common/tests/TestUtilities.Unicode/System/Text/Unicode/ParsedUnicodeData.cs @@ -151,7 +151,7 @@ namespace System.Text.Unicode string baseName = value.PropName[..^1]; for (int i = value.FirstCodePoint; i <= value.LastCodePoint /* inclusive */; i++) { - dict.Add(i, baseName + i.ToString("X4", CultureInfo.InvariantCulture)); + dict.Add(i, $"{baseName}{i:X4}"); } } } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft.CSharp.csproj b/src/libraries/Microsoft.CSharp/src/Microsoft.CSharp.csproj index 322c4c10680..8f9de151dfd 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft.CSharp.csproj +++ b/src/libraries/Microsoft.CSharp/src/Microsoft.CSharp.csproj @@ -247,6 +247,7 @@ + diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/VariantArray.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/VariantArray.cs index 289a0531458..9d2373f0b69 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/VariantArray.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/VariantArray.cs @@ -82,7 +82,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop // See if we can find an existing type foreach (Type t in s_generatedTypes) { - int arity = int.Parse(t.Name.Substring("VariantArray".Length), CultureInfo.InvariantCulture); + int arity = int.Parse(t.Name.AsSpan("VariantArray".Length), provider: CultureInfo.InvariantCulture); if (size == arity) { return t; diff --git a/src/libraries/Microsoft.Win32.Primitives/src/System/ComponentModel/Win32Exception.cs b/src/libraries/Microsoft.Win32.Primitives/src/System/ComponentModel/Win32Exception.cs index bf78cbc03c9..e3159637dc7 100644 --- a/src/libraries/Microsoft.Win32.Primitives/src/System/ComponentModel/Win32Exception.cs +++ b/src/libraries/Microsoft.Win32.Primitives/src/System/ComponentModel/Win32Exception.cs @@ -91,11 +91,11 @@ namespace System.ComponentModel : NativeErrorCode.ToString(CultureInfo.InvariantCulture); if (HResult == E_FAIL) { - s.AppendFormat(CultureInfo.InvariantCulture, " ({0})", nativeErrorString); + s.AppendFormat($" ({nativeErrorString})"); } else { - s.AppendFormat(CultureInfo.InvariantCulture, " ({0:X8}, {1})", HResult, nativeErrorString); + s.AppendFormat($" ({HResult:X8}, {nativeErrorString})"); } if (!(string.IsNullOrEmpty(message))) diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs index 16b3d1aecfb..7e9998e9516 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs @@ -173,7 +173,7 @@ namespace Microsoft.Win32 } // We really should throw an exception here if errorCode was bad, // but we can't for compatibility reasons. - Debug.Assert(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode); + Debug.Assert(errorCode == 0, $"RegDeleteValue failed. Here's your error code: {errorCode}"); } /// diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs index 0d7bc48f361..356529d80d2 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs @@ -793,12 +793,12 @@ namespace Microsoft.CSharp if (b == null) { Output.Write("\\u"); - Output.Write(((int)value).ToString("X4", CultureInfo.InvariantCulture)); + Output.Write(((int)value).ToString("X4")); } else { b.Append("\\u"); - b.Append(((int)value).ToString("X4", CultureInfo.InvariantCulture)); + b.Append(((int)value).ToString("X4")); } } @@ -2501,7 +2501,7 @@ namespace Microsoft.CSharp { foreach (byte b in checksumPragma.ChecksumData) { - Output.Write(b.ToString("X2", CultureInfo.InvariantCulture)); + Output.Write(b.ToString("X2")); } } Output.WriteLine("\""); diff --git a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs index a25eb3ed7f4..5c55dfc0650 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs @@ -2273,7 +2273,7 @@ namespace Microsoft.VisualBasic { foreach (byte b in checksumPragma.ChecksumData) { - Output.Write(b.ToString("X2", CultureInfo.InvariantCulture)); + Output.Write(b.ToString("X2")); } } Output.WriteLine("\")"); diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs index 1433e38cf95..3d494454c0f 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs @@ -707,9 +707,9 @@ namespace System.Collections.Concurrent internal bool GrabChunk_Single(KeyValuePair[] destArray, int requestedChunkSize, ref int actualNumElementsGrabbed) { Debug.Assert(_useSingleChunking, "Expected _useSingleChecking to be true"); - Debug.Assert(requestedChunkSize == 1, "Got requested chunk size of " + requestedChunkSize + " when single-chunking was on"); - Debug.Assert(actualNumElementsGrabbed == 0, "Expected actualNumElementsGrabbed == 0, instead it is " + actualNumElementsGrabbed); - Debug.Assert(destArray.Length == 1, "Expected destArray to be of length 1, instead its length is " + destArray.Length); + Debug.Assert(requestedChunkSize == 1, $"Got requested chunk size of {requestedChunkSize} when single-chunking was on"); + Debug.Assert(actualNumElementsGrabbed == 0, $"Expected actualNumElementsGrabbed == 0, instead it is {actualNumElementsGrabbed}"); + Debug.Assert(destArray.Length == 1, $"Expected destArray to be of length 1, instead its length is {destArray.Length}"); lock (_sharedLock) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs index 907b838a8f7..999a67dc439 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericServices.cs @@ -79,7 +79,7 @@ namespace System.ComponentModel.Composition.ReflectionModel string[] genericFormatArgs = new string[genericArity]; for (int i = 0; i < genericParametersOrder.Length; i++) { - genericFormatArgs[genericParametersOrder[i]] = string.Format(CultureInfo.InvariantCulture, "{{{0}}}", i); + genericFormatArgs[genericParametersOrder[i]] = $"{{{i}}}"; } return string.Format(CultureInfo.InvariantCulture, originalGenericName, genericFormatArgs); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/CommandID.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/CommandID.cs index 5640c431c5e..827acc9c4e8 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/CommandID.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/CommandID.cs @@ -46,6 +46,6 @@ namespace System.ComponentModel.Design /// /// Overrides Object's ToString method. /// - public override string ToString() => Guid.ToString() + " : " + ID.ToString(CultureInfo.CurrentCulture); + public override string ToString() => $"{Guid} : {ID}"; } } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs index f41b9fca2a1..ef3cc90c16d 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs @@ -1114,7 +1114,7 @@ namespace System.ComponentModel #if DEBUG foreach (EventDescriptor dbgEvent in events) { - Debug.Assert(dbgEvent != null, "Holes in event array for type " + type); + Debug.Assert(dbgEvent != null, $"Holes in event array for type {type}"); } #endif eventCache[type] = events; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtilWriter.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtilWriter.cs index 9094bc6c449..69017ea3367 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtilWriter.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/XmlUtilWriter.cs @@ -176,7 +176,7 @@ namespace System.Configuration internal int AppendCharEntity(char ch) { - string numberToWrite = ((int)ch).ToString("X", CultureInfo.InvariantCulture); + string numberToWrite = ((int)ch).ToString("X"); Write('&'); Write('#'); Write('x'); diff --git a/src/libraries/System.Console/src/System/TermInfo.cs b/src/libraries/System.Console/src/System/TermInfo.cs index eb545649d36..19e94551a6f 100644 --- a/src/libraries/System.Console/src/System/TermInfo.cs +++ b/src/libraries/System.Console/src/System/TermInfo.cs @@ -245,9 +245,10 @@ namespace System return null; } + Span stackBuffer = stackalloc char[256]; SafeFileHandle? fd; - if (!TryOpen(directoryPath + "/" + term[0].ToString() + "/" + term, out fd) && // /directory/termFirstLetter/term (Linux) - !TryOpen(directoryPath + "/" + ((int)term[0]).ToString("X") + "/" + term, out fd)) // /directory/termFirstLetterAsHex/term (Mac) + if (!TryOpen(string.Create(null, stackBuffer, $"{directoryPath}/{term[0]}/{term}"), out fd) && // /directory/termFirstLetter/term (Linux) + !TryOpen(string.Create(null, stackBuffer, $"{directoryPath}/{(int)term[0]:X}/{term}"), out fd)) // /directory/termFirstLetterAsHex/term (Mac) { return null; } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs index 27ffe33faa3..1b6c5fe1b7e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs @@ -242,7 +242,7 @@ namespace System.Data.Common { keylist.MoveNext(); values[i] = this[keylist.Current]; - Debug.Assert(null != values[i], "null value " + keylist.Current); + Debug.Assert(null != values[i], $"null value {keylist.Current}"); } return new ReadOnlyCollection(values); } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataException.cs b/src/libraries/System.Data.Common/src/System/Data/DataException.cs index 301075bf543..91409b4aa8c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataException.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataException.cs @@ -649,7 +649,7 @@ namespace System.Data public static Exception RangeArgument(int min, int max) => _Argument(SR.Format(SR.Range_Argument, (min).ToString(CultureInfo.InvariantCulture), (max).ToString(CultureInfo.InvariantCulture))); public static Exception NullRange() => _Data(SR.Range_NullRange); public static Exception NegativeMinimumCapacity() => _Argument(SR.RecordManager_MinimumCapacity); - public static Exception ProblematicChars(char charValue) => _Argument(SR.Format(SR.DataStorage_ProblematicChars, "0x" + ((ushort)charValue).ToString("X", CultureInfo.InvariantCulture))); + public static Exception ProblematicChars(char charValue) => _Argument(SR.Format(SR.DataStorage_ProblematicChars, $"0x{(ushort)charValue:X}")); public static Exception StorageSetFailed() => _Argument(SR.DataStorage_SetInvalidDataType); diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs index 0dca43b20ca..edefa695a40 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/AggregateNode.cs @@ -114,7 +114,7 @@ namespace System.Data // add column to the dependency list, do not add duplicate columns - Debug.Assert(_column != null, "Failed to bind column " + _columnName); + Debug.Assert(_column != null, $"Failed to bind column {_columnName}"); int i; for (i = 0; i < list.Count; i++) diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs index 79577f945b9..2202a8c9f81 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/FunctionNode.cs @@ -318,7 +318,7 @@ namespace System.Data switch (id) { case FunctionId.Abs: - Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); + Debug.Assert(_argumentCount == 1, $"Invalid argument argumentCount for {s_funcs[_info]._name} : {_argumentCount.ToString(FormatProvider)}"); storageType = DataStorage.GetStorageType(argumentValues[0].GetType()); if (ExpressionNode.IsInteger(storageType)) @@ -329,7 +329,7 @@ namespace System.Data throw ExprException.ArgumentTypeInteger(s_funcs[_info]._name, 1); case FunctionId.cBool: - Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); + Debug.Assert(_argumentCount == 1, $"Invalid argument argumentCount for {s_funcs[_info]._name} : {_argumentCount.ToString(FormatProvider)}"); storageType = DataStorage.GetStorageType(argumentValues[0].GetType()); return storageType switch @@ -341,26 +341,26 @@ namespace System.Data _ => throw ExprException.DatatypeConvertion(argumentValues[0].GetType(), typeof(bool)), }; case FunctionId.cInt: - Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); + Debug.Assert(_argumentCount == 1, $"Invalid argument argumentCount for {s_funcs[_info]._name} : {_argumentCount.ToString(FormatProvider)}"); return Convert.ToInt32(argumentValues[0], FormatProvider); case FunctionId.cDate: - Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); + Debug.Assert(_argumentCount == 1, $"Invalid argument argumentCount for {s_funcs[_info]._name} : {_argumentCount.ToString(FormatProvider)}"); return Convert.ToDateTime(argumentValues[0], FormatProvider); case FunctionId.cDbl: - Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); + Debug.Assert(_argumentCount == 1, $"Invalid argument argumentCount for {s_funcs[_info]._name} : {_argumentCount.ToString(FormatProvider)}"); return Convert.ToDouble(argumentValues[0], FormatProvider); case FunctionId.cStr: - Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); + Debug.Assert(_argumentCount == 1, $"Invalid argument argumentCount for {s_funcs[_info]._name} : {_argumentCount.ToString(FormatProvider)}"); return Convert.ToString(argumentValues[0], FormatProvider)!; case FunctionId.Charindex: - Debug.Assert(_argumentCount == 2, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); + Debug.Assert(_argumentCount == 2, $"Invalid argument argumentCount for {s_funcs[_info]._name} : {_argumentCount.ToString(FormatProvider)}"); - Debug.Assert(argumentValues[0] is string, "Invalid argument type for " + s_funcs[_info]._name); - Debug.Assert(argumentValues[1] is string, "Invalid argument type for " + s_funcs[_info]._name); + Debug.Assert(argumentValues[0] is string, $"Invalid argument type for {s_funcs[_info]._name}"); + Debug.Assert(argumentValues[1] is string, $"Invalid argument type for {s_funcs[_info]._name}"); if (DataStorage.IsObjectNull(argumentValues[0]) || DataStorage.IsObjectNull(argumentValues[1])) return DBNull.Value; @@ -374,7 +374,7 @@ namespace System.Data return ((string)argumentValues[1]).IndexOf((string)argumentValues[0], StringComparison.Ordinal); case FunctionId.Iif: - Debug.Assert(_argumentCount == 3, "Invalid argument argumentCount: " + _argumentCount.ToString(FormatProvider)); + Debug.Assert(_argumentCount == 3, $"Invalid argument argumentCount: {_argumentCount.ToString(FormatProvider)}"); object first = _arguments![0].Eval(row, version); @@ -401,8 +401,8 @@ namespace System.Data return argumentValues[0]; case FunctionId.Len: - Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); - Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid argument type for " + s_funcs[_info]._name); + Debug.Assert(_argumentCount == 1, $"Invalid argument argumentCount for {s_funcs[_info]._name} : {_argumentCount.ToString(FormatProvider)}"); + Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), $"Invalid argument type for {s_funcs[_info]._name}"); if (argumentValues[0] is SqlString) { @@ -420,10 +420,10 @@ namespace System.Data case FunctionId.Substring: - Debug.Assert(_argumentCount == 3, "Invalid argument argumentCount: " + _argumentCount.ToString(FormatProvider)); - Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid first argument " + argumentValues[0].GetType().FullName + " in " + s_funcs[_info]._name); - Debug.Assert(argumentValues[1] is int, "Invalid second argument " + argumentValues[1].GetType().FullName + " in " + s_funcs[_info]._name); - Debug.Assert(argumentValues[2] is int, "Invalid third argument " + argumentValues[2].GetType().FullName + " in " + s_funcs[_info]._name); + Debug.Assert(_argumentCount == 3, $"Invalid argument argumentCount: {_argumentCount.ToString(FormatProvider)}"); + Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), $"Invalid first argument {argumentValues[0].GetType().FullName} in {s_funcs[_info]._name}"); + Debug.Assert(argumentValues[1] is int, $"Invalid second argument {argumentValues[1].GetType().FullName} in {s_funcs[_info]._name}"); + Debug.Assert(argumentValues[2] is int, $"Invalid third argument {argumentValues[2].GetType().FullName} in {s_funcs[_info]._name}"); // work around the differences in .NET and VBA implementation of the Substring function // 1. The Argument is 0-based in .NET, and 1-based in VBA @@ -462,8 +462,8 @@ namespace System.Data case FunctionId.Trim: { - Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); - Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid argument type for " + s_funcs[_info]._name); + Debug.Assert(_argumentCount == 1, $"Invalid argument argumentCount for {s_funcs[_info]._name} : {_argumentCount.ToString(FormatProvider)}"); + Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), $"Invalid argument type for {s_funcs[_info]._name}"); if (DataStorage.IsObjectNull(argumentValues[0])) return DBNull.Value; diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs index ded0f3982a6..ea2cc9de54a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/NameNode.cs @@ -58,7 +58,7 @@ namespace System.Data _found = true; // add column to the dependency list, do not add duplicate columns - Debug.Assert(_column != null, "Failed to bind column " + _name); + Debug.Assert(_column != null, $"Failed to bind column {_name}"); int i; for (i = 0; i < list.Count; i++) diff --git a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs index 1d7ee94a478..39d130e4ff0 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs @@ -504,7 +504,7 @@ namespace System.Data internal void CheckCanRemoveParentRow(DataRow row) { - Debug.Assert(Table?.DataSet != null, "Relation " + ConstraintName + " isn't part of a DataSet, so this check shouldn't be happening."); + Debug.Assert(Table?.DataSet != null, $"Relation {ConstraintName} isn't part of a DataSet, so this check shouldn't be happening."); if (!Table.DataSet.EnforceConstraints) { return; @@ -517,7 +517,7 @@ namespace System.Data internal void CheckCascade(DataRow row, DataRowAction action) { - Debug.Assert(Table?.DataSet != null, "ForeignKeyConstraint " + ConstraintName + " isn't part of a DataSet, so this check shouldn't be happening."); + Debug.Assert(Table?.DataSet != null, $"ForeignKeyConstraint {ConstraintName} isn't part of a DataSet, so this check shouldn't be happening."); if (row._inCascade) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Merger.cs b/src/libraries/System.Data.Common/src/System/Data/Merger.cs index 5a4c7b1179f..616acba1372 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Merger.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Merger.cs @@ -608,7 +608,7 @@ namespace System.Data } else { - Debug.Assert(MissingSchemaAction.Error == _missingSchemaAction, "Unexpected value of MissingSchemaAction parameter : " + _missingSchemaAction.ToString()); + Debug.Assert(MissingSchemaAction.Error == _missingSchemaAction, $"Unexpected value of MissingSchemaAction parameter : {_missingSchemaAction}"); throw ExceptionBuilder.MergeMissingDefinition(relation.RelationName); } } diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs index 3792151f36d..a757be446e7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs @@ -119,8 +119,7 @@ namespace System.Data.SqlTypes /// /// Returns a string describing a object. /// - public override string ToString() => - _value is null ? SQLResource.NullString : "SqlBinary(" + _value.Length.ToString(CultureInfo.InvariantCulture) + ")"; + public override string ToString() => _value is null ? SQLResource.NullString : $"SqlBinary({_value.Length})"; // Unary operators diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs index fd41a8fb191..64e7815e294 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs @@ -1911,7 +1911,7 @@ namespace System.Data.SqlTypes private bool FGt10_38(Span rglData) { - Debug.Assert(rglData.Length == 4, "rglData.Length == 4", "Wrong array length: " + rglData.Length.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(rglData.Length == 4, "rglData.Length == 4", $"Wrong array length: {rglData.Length}"); return rglData[3] >= 0x4b3b4ca8L && ((rglData[3] > 0x4b3b4ca8L) || (rglData[2] > 0x5a86c47aL) || diff --git a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs index df76c1da336..a025c3f7f2b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs @@ -130,7 +130,7 @@ namespace System.Data internal bool IsTextOnlyContent(XmlElement node) { - Debug.Assert(FEqualIdentity(node, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS), "Invalid node type " + node.LocalName); + Debug.Assert(FEqualIdentity(node, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS), $"Invalid node type {node.LocalName}"); string value = node.GetAttribute(Keywords.CONTENT); if (value == null || value.Length == 0) @@ -282,12 +282,12 @@ namespace System.Data // Let's check that we realy don't have this name: foreach (NameType nt in s_mapNameTypeXdr) { - Debug.Assert(nt.name != name, "FindNameType('" + name + "') -- failed. Existed name not found"); + Debug.Assert(nt.name != name, $"FindNameType('{name}') -- failed. Existed name not found"); } #endif throw ExceptionBuilder.UndefinedDatatype(name); } - Debug.Assert(s_mapNameTypeXdr[index].name == name, "FindNameType('" + name + "') -- failed. Wrong name found"); + Debug.Assert(s_mapNameTypeXdr[index].name == name, $"FindNameType('{name}') -- failed. Wrong name found"); return s_mapNameTypeXdr[index]; } diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs index 1094e6ed536..ab2fef64dbc 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -1790,7 +1790,7 @@ namespace System.Data #if DEBUG for (int i = 1; i < s_mapNameTypeXsd.Length; ++i) { - Debug.Assert((s_mapNameTypeXsd[i - 1].CompareTo(s_mapNameTypeXsd[i].name)) < 0, "incorrect sorting " + s_mapNameTypeXsd[i].name); + Debug.Assert((s_mapNameTypeXsd[i - 1].CompareTo(s_mapNameTypeXsd[i].name)) < 0, $"incorrect sorting {s_mapNameTypeXsd[i].name}"); } #endif int index = Array.BinarySearch(s_mapNameTypeXsd, xsdTypeName); @@ -1856,7 +1856,7 @@ namespace System.Data #if DEBUG for (int i = 1; i < s_mapNameTypeXsd.Length; ++i) { - Debug.Assert((s_mapNameTypeXsd[i - 1].CompareTo(s_mapNameTypeXsd[i].name)) < 0, "incorrect sorting " + s_mapNameTypeXsd[i].name); + Debug.Assert((s_mapNameTypeXsd[i - 1].CompareTo(s_mapNameTypeXsd[i].name)) < 0, $"incorrect sorting {s_mapNameTypeXsd[i].name}"); } #endif int index = Array.BinarySearch(s_mapNameTypeXsd, name); @@ -1904,7 +1904,7 @@ namespace System.Data #if DEBUG for (int i = 1; i < s_mapNameTypeXsd.Length; ++i) { - Debug.Assert((s_mapNameTypeXsd[i - 1].CompareTo(s_mapNameTypeXsd[i].name)) < 0, "incorrect sorting " + s_mapNameTypeXsd[i].name); + Debug.Assert((s_mapNameTypeXsd[i - 1].CompareTo(s_mapNameTypeXsd[i].name)) < 0, $"incorrect sorting {s_mapNameTypeXsd[i].name}"); } #endif int index = Array.BinarySearch(s_mapNameTypeXsd, name); @@ -1914,12 +1914,12 @@ namespace System.Data // Let's check that we realy don't have this name: foreach (NameType nt in s_mapNameTypeXsd) { - Debug.Assert(nt.name != name, "FindNameType('" + name + "') -- failed. Existed name not found"); + Debug.Assert(nt.name != name, $"FindNameType('{name}') -- failed. Existed name not found"); } #endif return false; } - Debug.Assert(s_mapNameTypeXsd[index].name == name, "FindNameType('" + name + "') -- failed. Wrong name found"); + Debug.Assert(s_mapNameTypeXsd[index].name == name, $"FindNameType('{name}') -- failed. Wrong name found"); return true; } diff --git a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs index 46ad2ac3a80..a65a2798e5f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs +++ b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs @@ -1295,7 +1295,7 @@ namespace System.Data { #if DEBUG // enzol: TO DO: replace the constructor with IsEqual(XmlElement) - // Debug.Assert(col.SimpleType.IsEqual(new SimpleType(elmSimpeType)), "simpleTypes with the same name have to be the same: "+name); + // Debug.Assert(col.SimpleType.IsEqual(new SimpleType(elmSimpeType)), $"simpleTypes with the same name have to be the same: {name}"); #endif } } diff --git a/src/libraries/System.Data.Common/tests/System/Data/DataSetTest2.cs b/src/libraries/System.Data.Common/tests/System/Data/DataSetTest2.cs index d5943b3da38..f2d3d31cdfe 100644 --- a/src/libraries/System.Data.Common/tests/System/Data/DataSetTest2.cs +++ b/src/libraries/System.Data.Common/tests/System/Data/DataSetTest2.cs @@ -435,7 +435,7 @@ namespace System.Data.Tests StringBuilder resultXML = new StringBuilder(); - resultXML.Append("<" + ds.DataSetName + "xmlns=\"namespace\">"); + resultXML.Append($"<{ds.DataSetName}xmlns=\"namespace\">"); resultXML.Append(""); resultXML.Append("1"); @@ -455,7 +455,7 @@ namespace System.Data.Tests resultXML.Append("Value5"); resultXML.Append(""); - resultXML.Append(""); + resultXML.Append($""); ds.Tables.Add(dt); string strXML = ds.GetXml(); diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs index 08c95dc69d0..7bcba69eb24 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs @@ -527,7 +527,7 @@ namespace System.Data.Odbc } } } - Debug.Assert((0 <= ccb) && (ccb < 0x3fffffff), "GetParameterSize: out of range " + ccb); + Debug.Assert((0 <= ccb) && (ccb < 0x3fffffff), $"GetParameterSize: out of range {ccb}"); return ccb; } diff --git a/src/libraries/System.Data.Odbc/tests/TestCommon/DataTestUtility.cs b/src/libraries/System.Data.Odbc/tests/TestCommon/DataTestUtility.cs index 5055dfb97ce..b563a7e7b85 100644 --- a/src/libraries/System.Data.Odbc/tests/TestCommon/DataTestUtility.cs +++ b/src/libraries/System.Data.Odbc/tests/TestCommon/DataTestUtility.cs @@ -23,12 +23,7 @@ namespace System.Data.Odbc.Tests // some providers does not support names (Oracle supports up to 30) public static string GetUniqueName(string prefix, string escapeLeft, string escapeRight) { - string uniqueName = string.Format("{0}{1}_{2}_{3}{4}", - escapeLeft, - prefix, - DateTime.Now.Ticks.ToString("X", CultureInfo.InvariantCulture), // up to 8 characters - Guid.NewGuid().ToString().Substring(0, 6), // take the first 6 characters only - escapeRight); + string uniqueName = $"{escapeLeft}{prefix}_{DateTime.Now.Ticks:X}_{Guid.NewGuid().ToString().Substring(0, 6)}{escapeRight}"; return uniqueName; } diff --git a/src/libraries/System.Data.OleDb/src/ColumnBinding.cs b/src/libraries/System.Data.OleDb/src/ColumnBinding.cs index 8eca4d62806..344ccae3b8a 100644 --- a/src/libraries/System.Data.OleDb/src/ColumnBinding.cs +++ b/src/libraries/System.Data.OleDb/src/ColumnBinding.cs @@ -55,7 +55,7 @@ namespace System.Data.OleDb { Debug.Assert(null != rowbinding, "null rowbinding"); Debug.Assert(null != bindings, "null bindings"); - Debug.Assert(ODB.SizeOf_tagDBBINDING <= offset, "invalid offset" + offset); + Debug.Assert(ODB.SizeOf_tagDBBINDING <= offset, $"invalid offset {offset}"); _dataReader = dataReader; _rowbinding = rowbinding; diff --git a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs index 2d47d32c4d9..afce7a7dbc3 100644 --- a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs +++ b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs @@ -844,8 +844,8 @@ namespace System.Data.Common string keyname = (string)entry.Key; string? value1 = (string?)entry.Value; string? value2 = (string?)parsetable[keyname]; - Debug.Assert(parsetable.Contains(keyname), "ParseInternal code vs. regex mismatch keyname <" + keyname + ">"); - Debug.Assert(value1 == value2, "ParseInternal code vs. regex mismatch keyvalue <" + value1 + "> <" + value2 + ">"); + Debug.Assert(parsetable.Contains(keyname), $"ParseInternal code vs. regex mismatch keyname <{keyname}>"); + Debug.Assert(value1 == value2, $"ParseInternal code vs. regex mismatch keyvalue <{value1}> <{value2}>"); } } @@ -871,11 +871,11 @@ namespace System.Data.Common } } } - Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <" + msg1 + "> <" + msg2 + ">"); + Debug.Assert(isEquivalent, $"ParseInternal code vs regex message mismatch: <{msg1}> <{msg2}>"); } else { - Debug.Assert(false, "ParseInternal code vs regex throw mismatch " + f.Message); + Debug.Assert(false, $"ParseInternal code vs regex throw mismatch {f.Message}"); } e = null; } diff --git a/src/libraries/System.Data.OleDb/src/DbPropSet.cs b/src/libraries/System.Data.OleDb/src/DbPropSet.cs index 756c4612c3f..c0b719c7373 100644 --- a/src/libraries/System.Data.OleDb/src/DbPropSet.cs +++ b/src/libraries/System.Data.OleDb/src/DbPropSet.cs @@ -254,7 +254,7 @@ namespace System.Data.OleDb for (int i = 0; i < properties.Length; ++i) { - Debug.Assert(null != properties[i], "null tagDBPROP " + i.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(null != properties[i], $"null tagDBPROP {i.ToString(CultureInfo.InvariantCulture)}"); IntPtr propertyPtr = ADP.IntPtrOffset(propset.rgProperties, i * ODB.SizeOf_tagDBPROP); Marshal.StructureToPtr(properties[i], propertyPtr, false/*deleteold*/); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs index 6417087aa62..8d78f2ac493 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs @@ -235,7 +235,7 @@ namespace System.Data.OleDb break; default: // have to assume everything is okay - Debug.Assert(false, "Unknown 'Connection Status' value " + connectionStatus.ToString("G", CultureInfo.InvariantCulture)); + Debug.Assert(false, $"Unknown 'Connection Status' value {connectionStatus.ToString("G", CultureInfo.InvariantCulture)}"); break; } } diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs index e50ba5a23b1..e305bfd0416 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs @@ -584,7 +584,7 @@ namespace System.Data.OleDb #if DEBUG if (AdapterSwitches.DataSchema.TraceVerbose) { - Debug.WriteLine("OleDbDataReader[" + info.ordinal.ToInt64().ToString(CultureInfo.InvariantCulture) + ", " + dbColumnInfo.pwszName + "]=" + dbType.enumOleDbType.ToString() + "," + dbType.dataSourceType + ", " + dbType.wType); + Debug.WriteLine($"OleDbDataReader[{info.ordinal}, {dbColumnInfo.pwszName}]={dbType.enumOleDbType},{dbType.dataSourceType}, {dbType.wType}"); } #endif rowCount++; @@ -2108,7 +2108,7 @@ namespace System.Data.OleDb #if DEBUG if (AdapterSwitches.DataSchema.TraceVerbose) { - Debug.WriteLine("PartialKeyColumn detected: <" + name + "> metaindex=" + metaindex); + Debug.WriteLine($"PartialKeyColumn detected: <{name}> metaindex={metaindex}"); } #endif partialPrimaryKey = true; @@ -2199,7 +2199,7 @@ namespace System.Data.OleDb #if DEBUG if (AdapterSwitches.DataSchema.TraceVerbose) { - Debug.WriteLine("MultipleUniqueIndexes detected: <" + uniqueIndexName + "> <" + indexname + ">"); + Debug.WriteLine($"MultipleUniqueIndexes detected: <{uniqueIndexName}> <{indexname}>"); } #endif uniq = null; @@ -2211,7 +2211,7 @@ namespace System.Data.OleDb #if DEBUG if (AdapterSwitches.DataSchema.TraceVerbose) { - Debug.WriteLine("PartialKeyColumn detected: " + name); + Debug.WriteLine($"PartialKeyColumn detected: {name}"); } #endif partialPrimaryKey = true; @@ -2226,7 +2226,7 @@ namespace System.Data.OleDb #if DEBUG if (AdapterSwitches.DataSchema.TraceVerbose) { - Debug.WriteLine("PartialUniqueIndexes detected: <" + uniqueIndexName + "> <" + indexname + ">"); + Debug.WriteLine($"PartialUniqueIndexes detected: <{uniqueIndexName}> <{indexname}>"); } #endif uniq = null; @@ -2247,7 +2247,7 @@ namespace System.Data.OleDb #if DEBUG if (AdapterSwitches.DataSchema.TraceVerbose) { - Debug.WriteLine("upgrade single unique index to be a key: <" + uniqueIndexName + ">"); + Debug.WriteLine($"upgrade single unique index to be a key: <{uniqueIndexName}>"); } #endif // upgrade single unique index to be a key @@ -2498,7 +2498,7 @@ namespace System.Data.OleDb #if DEBUG if (AdapterSwitches.DataSchema.TraceVerbose) { - Debug.WriteLine("Filtered Column: DBCOLUMN_GUID=DBCOL_SPECIALCOL DBCOLUMN_NAME=" + info.columnName + " DBCOLUMN_KEYCOLUMN=" + info.isKeyColumn); + Debug.WriteLine($"Filtered Column: DBCOLUMN_GUID=DBCOL_SPECIALCOL DBCOLUMN_NAME={info.columnName} DBCOLUMN_KEYCOLUMN={info.isKeyColumn}"); } #endif info.isHidden = true; @@ -2509,7 +2509,7 @@ namespace System.Data.OleDb #if DEBUG if (AdapterSwitches.DataSchema.TraceVerbose) { - Debug.WriteLine("Filtered Column: DBCOLUMN_NUMBER=" + info.ordinal.ToInt64().ToString(CultureInfo.InvariantCulture) + " DBCOLUMN_NAME=" + info.columnName); + Debug.WriteLine($"Filtered Column: DBCOLUMN_NUMBER={info.ordinal} DBCOLUMN_NAME={info.columnName}"); } #endif info.isHidden = true; @@ -2520,7 +2520,7 @@ namespace System.Data.OleDb #if DEBUG if (AdapterSwitches.DataSchema.TraceVerbose) { - Debug.WriteLine("Filtered Column: DBCOLUMN_FLAGS=" + info.flags.ToString("X8", null) + " DBCOLUMN_NAME=" + info.columnName); + Debug.WriteLine($"Filtered Column: DBCOLUMN_FLAGS={info.flags:X8} DBCOLUMN_NAME={info.columnName}"); } #endif info.isHidden = true; diff --git a/src/libraries/System.Data.OleDb/src/OleDbStruct.cs b/src/libraries/System.Data.OleDb/src/OleDbStruct.cs index 69a0e4807db..0c7dd5ad35c 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbStruct.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbStruct.cs @@ -52,10 +52,10 @@ namespace System.Data.OleDb { builder.Append("pwszDataSourceType =").Append(Marshal.PtrToStringUni(pwszDataSourceType)).Append(Environment.NewLine); } - builder.Append("\tulParamSize =" + ulParamSize.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tdwFlags =0x" + dwFlags.ToString("X4", CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tPrecision =" + bPrecision.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tScale =" + bScale.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); + builder.AppendLine($"\tulParamSize ={ulParamSize}"); + builder.AppendLine($"\tdwFlags =0x{dwFlags:X4}"); + builder.AppendLine($"\tPrecision ={bPrecision}"); + builder.AppendLine($"\tScale ={bScale}"); return builder.ToString(); } #endif @@ -78,12 +78,12 @@ namespace System.Data.OleDb builder.Append("tagDBPARAMBINDINFO").Append(Environment.NewLine); if (IntPtr.Zero != pwszDataSourceType) { - builder.Append("pwszDataSourceType =").Append(Marshal.PtrToStringUni(pwszDataSourceType)).Append(Environment.NewLine); + builder.AppendLine($"pwszDataSourceType ={Marshal.PtrToStringUni(pwszDataSourceType)}"); } - builder.Append("\tulParamSize =" + ulParamSize.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tdwFlags =0x" + dwFlags.ToString("X4", CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tPrecision =" + bPrecision.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tScale =" + bScale.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); + builder.AppendLine($"\tulParamSize ={ulParamSize}"); + builder.AppendLine($"\tdwFlags =0x{dwFlags:X4}"); + builder.AppendLine($"\tPrecision ={bPrecision}"); + builder.AppendLine($"\tScale ={bScale}"); return builder.ToString(); } #endif @@ -144,15 +144,15 @@ namespace System.Data.OleDb public override string ToString() { StringBuilder builder = new StringBuilder(); - builder.Append("tagDBBINDING").Append(Environment.NewLine); - builder.Append("\tOrdinal =" + iOrdinal.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tValueOffset =" + obValue.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tLengthOffset=" + obLength.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tStatusOffset=" + obStatus.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tMaxLength =" + cbMaxLen.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tDB_Type =" + ODB.WLookup(wType)).Append(Environment.NewLine); - builder.Append("\tPrecision =" + bPrecision.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\tScale =" + bScale.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); + builder.AppendLine("tagDBBINDING"); + builder.AppendLine($"\tOrdinal ={iOrdinal}"); + builder.AppendLine($"\tValueOffset ={obValue}"); + builder.AppendLine($"\tLengthOffset={obLength}"); + builder.AppendLine($"\tStatusOffset={obStatus}"); + builder.AppendLine($"\tMaxLength ={cbMaxLen}"); + builder.AppendLine($"\tDB_Type ={ODB.WLookup(wType)}"); + builder.AppendLine($"\tPrecision ={bPrecision}"); + builder.AppendLine($"\tScale ={bScale}"); return builder.ToString(); } #endif @@ -442,14 +442,14 @@ namespace System.Data.OleDb public override string ToString() { StringBuilder builder = new StringBuilder(); - builder.Append("tagDBCOLUMNINFO: " + Convert.ToString(pwszName, CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\t" + iOrdinal.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\t" + "0x" + dwFlags.ToString("X8", CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\t" + ulColumnSize.ToInt64().ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\t" + "0x" + wType.ToString("X2", CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\t" + bPrecision.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\t" + bScale.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); - builder.Append("\t" + columnid.eKind.ToString(CultureInfo.InvariantCulture)).Append(Environment.NewLine); + builder.AppendLine($"tagDBCOLUMNINFO: {Convert.ToString(pwszName, CultureInfo.InvariantCulture)}"); + builder.AppendLine($"\t{iOrdinal.ToInt64().ToString(CultureInfo.InvariantCulture)}"); + builder.AppendLine($"\t0x{dwFlags:X8}"); + builder.AppendLine($"\t{ulColumnSize}"); + builder.AppendLine($"\t0x{wType:X2}"); + builder.AppendLine($"\t{bPrecision}"); + builder.AppendLine($"\t{bScale}"); + builder.AppendLine($"\t{columnid.eKind}"); return builder.ToString(); } #endif diff --git a/src/libraries/System.Data.OleDb/src/OleDb_Util.cs b/src/libraries/System.Data.OleDb/src/OleDb_Util.cs index b0a39dea96c..1426320311c 100644 --- a/src/libraries/System.Data.OleDb/src/OleDb_Util.cs +++ b/src/libraries/System.Data.OleDb/src/OleDb_Util.cs @@ -697,9 +697,7 @@ namespace System.Data.OleDb { builder.Length = 0; } - builder.Append("(0x"); - builder.Append(((int)hr).ToString("X8", CultureInfo.InvariantCulture)); - builder.Append(')'); + builder.Append($"(0x{(int)hr:X8})"); return builder.ToString(); } @@ -710,9 +708,7 @@ namespace System.Data.OleDb string? value = (string?)g_wlookpup[id]; if (null == value) { - value = "0x" + ((short)id).ToString("X2", CultureInfo.InvariantCulture) + " " + ((short)id); - value += " " + ((DBTypeEnum)id).ToString(); - g_wlookpup[id] = value; + g_wlookpup[id] = value = $"0x{(short)id:X2} {(short)id} {(DBTypeEnum)id}"; } return value; } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs b/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs index f5bacfd6239..473789ae89f 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/Common/AdapterUtil.cs @@ -266,7 +266,7 @@ namespace System.Data.Common case CommandType.Text: case CommandType.StoredProcedure: case CommandType.TableDirect: - Debug.Assert(false, "valid CommandType " + value.ToString()); + Debug.Assert(false, $"valid CommandType {value}"); break; } #endif @@ -283,7 +283,7 @@ namespace System.Data.Common case DataRowVersion.Current: case DataRowVersion.Original: case DataRowVersion.Proposed: - Debug.Assert(false, "valid DataRowVersion " + value.ToString()); + Debug.Assert(false, $"valid DataRowVersion {value}"); break; } #endif @@ -303,7 +303,7 @@ namespace System.Data.Common case IsolationLevel.RepeatableRead: case IsolationLevel.Serializable: case IsolationLevel.Snapshot: - Debug.Assert(false, "valid IsolationLevel " + value.ToString()); + Debug.Assert(false, $"valid IsolationLevel {value}"); break; } #endif @@ -320,7 +320,7 @@ namespace System.Data.Common case ParameterDirection.Output: case ParameterDirection.InputOutput: case ParameterDirection.ReturnValue: - Debug.Assert(false, "valid ParameterDirection " + value.ToString()); + Debug.Assert(false, $"valid ParameterDirection {value}"); break; } #endif @@ -337,7 +337,7 @@ namespace System.Data.Common case UpdateRowSource.OutputParameters: case UpdateRowSource.FirstReturnedRecord: case UpdateRowSource.Both: - Debug.Assert(false, "valid UpdateRowSource " + value.ToString()); + Debug.Assert(false, $"valid UpdateRowSource {value}"); break; } #endif diff --git a/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Windows.cs b/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Windows.cs index d92bd9471ba..ce77b52cc67 100644 --- a/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Windows.cs +++ b/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Windows.cs @@ -65,7 +65,7 @@ namespace System.Diagnostics private static string ConvertTo8DigitHex(uint value) { - return value.ToString("X8", CultureInfo.InvariantCulture); + return value.ToString("X8"); } private static Interop.Version.VS_FIXEDFILEINFO GetFixedFileInfo(IntPtr memPtr) @@ -126,18 +126,20 @@ namespace System.Diagnostics // private bool GetVersionInfoForCodePage(IntPtr memIntPtr, string codepage) { - _companyName = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\CompanyName"); - _fileDescription = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\FileDescription"); - _fileVersion = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\FileVersion"); - _internalName = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\InternalName"); - _legalCopyright = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\LegalCopyright"); - _originalFilename = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\OriginalFilename"); - _productName = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\ProductName"); - _productVersion = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\ProductVersion"); - _comments = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\Comments"); - _legalTrademarks = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\LegalTrademarks"); - _privateBuild = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\PrivateBuild"); - _specialBuild = GetFileVersionString(memIntPtr, $"\\\\StringFileInfo\\\\{codepage}\\\\SpecialBuild"); + Span stackBuffer = stackalloc char[256]; + + _companyName = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\CompanyName")); + _fileDescription = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\FileDescription")); + _fileVersion = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\FileVersion")); + _internalName = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\InternalName")); + _legalCopyright = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\LegalCopyright")); + _originalFilename = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\OriginalFilename")); + _productName = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\ProductName")); + _productVersion = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\ProductVersion")); + _comments = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\Comments")); + _legalTrademarks = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\LegalTrademarks")); + _privateBuild = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\PrivateBuild")); + _specialBuild = GetFileVersionString(memIntPtr, string.Create(null, stackBuffer, $"\\\\StringFileInfo\\\\{codepage}\\\\SpecialBuild")); _language = GetFileVersionLanguage(memIntPtr); diff --git a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs index 9c4015842b1..28325cc356a 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs @@ -240,7 +240,7 @@ namespace System.Diagnostics } catch (IOException) { - fileNameOnly = Guid.NewGuid().ToString() + fileNameOnly; + fileNameOnly = $"{Guid.NewGuid()}{fileNameOnly}"; fullPath = Path.Combine(dirPath, fileNameOnly); continue; } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs index 3935b1609fa..a8441268574 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs @@ -184,7 +184,7 @@ namespace System.Diagnostics public virtual void TraceTransfer(TraceEventCache? eventCache, string source, int id, string? message, Guid relatedActivityId) { - TraceEvent(eventCache, source, TraceEventType.Transfer, id, message + ", relatedActivityId=" + relatedActivityId.ToString()); + TraceEvent(eventCache, source, TraceEventType.Transfer, id, string.Create(null, stackalloc char[256], $"{message}, relatedActivityId={relatedActivityId}")); } /// @@ -201,8 +201,8 @@ namespace System.Diagnostics public virtual void Fail(string? message, string? detailMessage) { WriteLine(detailMessage is null ? - SR.TraceListenerFail + " " + message : - SR.TraceListenerFail + " " + message + " " + detailMessage); + $"{SR.TraceListenerFail} {message}" : + $"{SR.TraceListenerFail} {message} {detailMessage}"); } /// @@ -390,7 +390,7 @@ namespace System.Diagnostics private void WriteHeader(string source, TraceEventType eventType, int id) { - Write($"{source} {eventType.ToString()}: {id.ToString(CultureInfo.InvariantCulture)} : "); + Write(string.Create(CultureInfo.InvariantCulture, stackalloc char[256], $"{source} {eventType}: {id} : ")); } private void WriteFooter(TraceEventCache? eventCache) @@ -425,14 +425,16 @@ namespace System.Diagnostics WriteLine(string.Empty); } + Span stackBuffer = stackalloc char[128]; + if (IsEnabled(TraceOptions.ThreadId)) WriteLine("ThreadId=" + eventCache.ThreadId); if (IsEnabled(TraceOptions.DateTime)) - WriteLine("DateTime=" + eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture)); + WriteLine(string.Create(null, stackBuffer, $"DateTime={eventCache.DateTime:o}")); if (IsEnabled(TraceOptions.Timestamp)) - WriteLine("Timestamp=" + eventCache.Timestamp); + WriteLine(string.Create(null, stackBuffer, $"Timestamp={eventCache.Timestamp}")); if (IsEnabled(TraceOptions.Callstack)) WriteLine("Callstack=" + eventCache.Callstack); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Brush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Brush.cs index af4e81ea8af..de964a2b13d 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Brush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Brush.cs @@ -47,7 +47,7 @@ namespace System.Drawing #endif Gdip.GdipDeleteBrush(new HandleRef(this, _nativeBrush)); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex)) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Windows.cs index a1c04e7d2f5..f0a1bd9aec3 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Windows.cs @@ -94,7 +94,7 @@ namespace System.Drawing.Drawing2D #endif Gdip.GdipDeletePath(new HandleRef(this, _nativePath)); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPathIterator.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPathIterator.cs index 4b4135665ee..8e83841c4f6 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPathIterator.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPathIterator.cs @@ -38,7 +38,7 @@ namespace System.Drawing.Drawing2D #endif Gdip.GdipDeletePathIter(new HandleRef(this, nativeIter)); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/SafeCustomLineCapHandle.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/SafeCustomLineCapHandle.cs index b01b88392b9..410f4478913 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/SafeCustomLineCapHandle.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/SafeCustomLineCapHandle.cs @@ -48,7 +48,7 @@ namespace System.Drawing.Drawing2D { handle = IntPtr.Zero; } - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); } return status == Gdip.Ok; } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs index 91a932b60dc..8163d0eefb1 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs @@ -65,7 +65,7 @@ namespace System.Drawing int status = Gdip.GdipCreateFont(new HandleRef(this, family.NativeFamily), emSize, style, unit, out _nativeFont); if (status == Gdip.FontStyleNotFound) - throw new ArgumentException($"Style {style.ToString()} isn't supported by font {familyName}."); + throw new ArgumentException($"Style {style} isn't supported by font {familyName}."); Gdip.CheckStatus(status); } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs index 6634ee78841..0a738e0e3e8 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs @@ -183,7 +183,7 @@ namespace System.Drawing #endif Gdip.GdipDeleteFont(new HandleRef(this, _nativeFont)); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) when (!ClientUtils.IsCriticalException(ex)) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs index 5bb82adbc80..ace1758b4d5 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs @@ -40,7 +40,8 @@ namespace System.Drawing ValueStringBuilder sb = default; sb.Append(font.Name); - sb.Append(culture.TextInfo.ListSeparator[0] + " "); + sb.Append(culture.TextInfo.ListSeparator[0]); + sb.Append(" "); sb.Append(font.Size.ToString(culture.NumberFormat)); switch (font.Unit) @@ -79,7 +80,8 @@ namespace System.Drawing if (font.Style != FontStyle.Regular) { - sb.Append(culture.TextInfo.ListSeparator[0] + " style="); + sb.Append(culture.TextInfo.ListSeparator[0]); + sb.Append(" style="); sb.Append(font.Style.ToString()); } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs index 6e0438be885..89b80a06cbc 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs @@ -162,7 +162,7 @@ namespace System.Drawing #endif Gdip.GdipDeleteFontFamily(new HandleRef(this, _nativeFamily)); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) when (!ClientUtils.IsCriticalException(ex)) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs index 929ea19c4fa..8dd2ad15b22 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs @@ -178,7 +178,7 @@ namespace System.Drawing Gdip.GdipDeleteGraphics(new HandleRef(this, NativeGraphics)); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex)) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs index ccea5ff42d5..c359e7af7fd 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs @@ -95,7 +95,7 @@ namespace System.Drawing #endif Gdip.GdipDisposeImage(new HandleRef(this, nativeImage)); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/FrameDimension.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/FrameDimension.cs index 5fc556efad7..44d36d291cb 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/FrameDimension.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/FrameDimension.cs @@ -78,7 +78,7 @@ namespace System.Drawing.Imaging if (this == s_time) return "Time"; if (this == s_resolution) return "Resolution"; if (this == s_page) return "Page"; - return "[FrameDimension: " + _guid + "]"; + return $"[FrameDimension: {_guid}]"; } } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageAttributes.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageAttributes.cs index 5831014b1e6..dca1674b2d5 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageAttributes.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageAttributes.cs @@ -94,7 +94,7 @@ namespace System.Drawing.Imaging #endif Gdip.GdipDisposeImageAttributes(new HandleRef(this, nativeImageAttributes)); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageFormat.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageFormat.cs index 705fad55ee5..ca4e867fcba 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageFormat.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageFormat.cs @@ -170,7 +170,7 @@ namespace System.Drawing.Imaging if (this.Guid == s_tiff.Guid) return "Tiff"; if (this.Guid == s_exif.Guid) return "Exif"; if (this.Guid == s_icon.Guid) return "Icon"; - return "[ImageFormat: " + _guid + "]"; + return $"[ImageFormat: {_guid}]"; } } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs index 9d2343d83b5..8645b31c10c 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs @@ -55,7 +55,7 @@ namespace System.Drawing.Internal list[index] = new WeakReference(obj); else { - Debug.Assert(list[index].Target == null, "Trying to reuse a weak reference that isn't broken yet: list[" + index + "], length =" + list.Length); + Debug.Assert(list[index].Target == null, $"Trying to reuse a weak reference that isn't broken yet: list[{index}], length = {list.Length}"); list[index].Target = obj; } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs index 606f8cc57af..ca5d045000d 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs @@ -161,7 +161,7 @@ namespace System.Drawing #endif Gdip.GdipDeletePen(new HandleRef(this, NativePen)); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex)) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/Margins.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/Margins.cs index 39691a9ad5e..05764ce8f21 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/Margins.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/Margins.cs @@ -235,14 +235,6 @@ namespace System.Drawing.Printing /// /// Provides some interesting information for the Margins in String form. /// - public override string ToString() - { - return "[Margins" - + " Left=" + Left.ToString(CultureInfo.InvariantCulture) - + " Right=" + Right.ToString(CultureInfo.InvariantCulture) - + " Top=" + Top.ToString(CultureInfo.InvariantCulture) - + " Bottom=" + Bottom.ToString(CultureInfo.InvariantCulture) - + "]"; - } + public override string ToString() => $"[Margins Left={Left} Right={Right} Top={Top} Bottom={Bottom}]"; } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Unix.cs index a7e8c1dbdbc..a79fb02f0a2 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Unix.cs @@ -255,9 +255,7 @@ namespace System.Drawing.Printing throw new NotImplementedException(); } - public override string ToString() - { - return $"[{nameof(PageSettings)}: {nameof(Color)}={color}, {nameof(Landscape)}={landscape}, {nameof(Margins)}={margins}, {nameof(PaperSize)}={paperSize}, {nameof(PaperSource)}={paperSource}, {nameof(PrinterResolution)}={printerResolution}]"; - } + public override string ToString() => + $"[{nameof(PageSettings)}: {nameof(Color)}={color}, {nameof(Landscape)}={landscape}, {nameof(Margins)}={margins}, {nameof(PaperSize)}={paperSize}, {nameof(PaperSource)}={paperSource}, {nameof(PrinterResolution)}={printerResolution}]"; } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Windows.cs index 8ac8e9ce247..f0e41dbc667 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Windows.cs @@ -536,16 +536,7 @@ namespace System.Drawing.Printing /// /// Provides some interesting information about the PageSettings in String form. /// - public override string ToString() - { - return "[PageSettings:" - + " Color=" + Color.ToString() - + ", Landscape=" + Landscape.ToString() - + ", Margins=" + Margins.ToString() - + ", PaperSize=" + PaperSize.ToString() - + ", PaperSource=" + PaperSource.ToString() - + ", PrinterResolution=" + PrinterResolution.ToString() - + "]"; - } + public override string ToString() => + $"[{nameof(PageSettings)}: Color={Color}, Landscape={Landscape}, Margins={Margins}, PaperSize={PaperSize}, PaperSource={PaperSource}, PrinterResolution={PrinterResolution}]"; } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PaperSize.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PaperSize.cs index 34b12d52c9d..4b9b49ae33d 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PaperSize.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PaperSize.cs @@ -127,13 +127,6 @@ namespace System.Drawing.Printing /// /// Provides some interesting information about the PaperSize in String form. /// - public override string ToString() - { - return "[PaperSize " + PaperName - + " Kind=" + Kind.ToString() - + " Height=" + Height.ToString(CultureInfo.InvariantCulture) - + " Width=" + Width.ToString(CultureInfo.InvariantCulture) - + "]"; - } + public override string ToString() => $"[PaperSize {PaperName} Kind={Kind.ToString()} Height={Height.ToString(CultureInfo.InvariantCulture)} Width={Width.ToString(CultureInfo.InvariantCulture)}]"; } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PaperSource.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PaperSource.cs index 9db90421050..5a321cc4d81 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PaperSource.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PaperSource.cs @@ -63,11 +63,6 @@ namespace System.Drawing.Printing /// /// Provides some interesting information about the PaperSource in String form. /// - public override string ToString() - { - return "[PaperSource " + SourceName - + " Kind=" + Kind.ToString() - + "]"; - } + public override string ToString() => $"[PaperSource {SourceName} Kind={Kind}]"; } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Unix.cs index 25ea2116850..2d3306ed8a2 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Unix.cs @@ -187,10 +187,7 @@ namespace System.Drawing.Printing PrintController.OnEndPrint(this, printArgs); } - public override string ToString() - { - return "[PrintDocument " + this.DocumentName + "]"; - } + public override string ToString() => $"[PrintDocument {this.DocumentName}]"; // events protected virtual void OnBeginPrint(PrintEventArgs e) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Windows.cs index 3d0b09a7321..eaa73074f87 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Windows.cs @@ -248,9 +248,6 @@ namespace System.Drawing.Printing /// /// Provides some interesting information about the PrintDocument in String form. /// - public override string ToString() - { - return "[PrintDocument " + DocumentName + "]"; - } + public override string ToString() => $"[PrintDocument {DocumentName}]"; } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Unix.cs index d3e567777cd..4043ec72213 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Unix.cs @@ -365,13 +365,7 @@ namespace System.Drawing.Printing throw new NotImplementedException(); } - public override string ToString() - { - return "Printer [PrinterSettings " + printer_name + " Copies=" + copies + " Collate=" + collate - + " Duplex=" + can_duplex + " FromPage=" + from_page + " LandscapeAngle=" + landscape_angle - + " MaximumCopies=" + maximum_copies + " OutputPort=" + " ToPage=" + to_page + "]"; - - } + public override string ToString() => $"Printer [PrinterSettings {printer_name} Copies={copies} Collate={collate} Duplex={can_duplex} FromPage={from_page} LandscapeAngle={landscape_angle} MaximumCopies={maximum_copies} OutputPort= ToPage={to_page}]"; // Public subclasses #region Public Subclasses diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs index 1889516f87a..d750390d07d 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs @@ -1258,16 +1258,16 @@ namespace System.Drawing.Printing { string printerName = PrinterName; return "[PrinterSettings " - + printerName - + " Copies=" + Copies.ToString(CultureInfo.InvariantCulture) - + " Collate=" + Collate.ToString(CultureInfo.InvariantCulture) - + " Duplex=" + Duplex.ToString() - + " FromPage=" + FromPage.ToString(CultureInfo.InvariantCulture) - + " LandscapeAngle=" + LandscapeAngle.ToString(CultureInfo.InvariantCulture) - + " MaximumCopies=" + MaximumCopies.ToString(CultureInfo.InvariantCulture) - + " OutputPort=" + OutputPort.ToString(CultureInfo.InvariantCulture) - + " ToPage=" + ToPage.ToString(CultureInfo.InvariantCulture) - + "]"; + + printerName + + " Copies=" + Copies.ToString(CultureInfo.InvariantCulture) + + " Collate=" + Collate.ToString(CultureInfo.InvariantCulture) + + " Duplex=" + Duplex.ToString() + + " FromPage=" + FromPage.ToString(CultureInfo.InvariantCulture) + + " LandscapeAngle=" + LandscapeAngle.ToString(CultureInfo.InvariantCulture) + + " MaximumCopies=" + MaximumCopies.ToString(CultureInfo.InvariantCulture) + + " OutputPort=" + OutputPort.ToString(CultureInfo.InvariantCulture) + + " ToPage=" + ToPage.ToString(CultureInfo.InvariantCulture) + + "]"; } // Write null terminated string, return length of string in characters (including null) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs index d87c739d8ca..379fc61e2e1 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs @@ -101,7 +101,7 @@ namespace System.Drawing #endif Gdip.GdipDeleteRegion(new HandleRef(this, NativeRegion)); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex)) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs index 6a905918200..cd0a7d074d1 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs @@ -86,7 +86,7 @@ namespace System.Drawing #endif Gdip.GdipDeleteStringFormat(new HandleRef(this, nativeFormat)); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) @@ -442,9 +442,6 @@ namespace System.Drawing /// /// Converts this to a human-readable string. /// - public override string ToString() - { - return "[StringFormat, FormatFlags=" + FormatFlags.ToString() + "]"; - } + public override string ToString() => $"[StringFormat, FormatFlags={FormatFlags.ToString()}]"; } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs index 8541e3069c2..609ccae35b8 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs @@ -37,7 +37,7 @@ namespace System.Drawing.Text #endif Gdip.GdipDeletePrivateFontCollection(ref _nativeFontCollection); #if DEBUG - Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); + Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); #endif } catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex)) diff --git a/src/libraries/System.Drawing.Primitives/src/System/Drawing/Color.cs b/src/libraries/System.Drawing.Primitives/src/System/Drawing/Color.cs index f711d9a5fe6..a7f116edada 100644 --- a/src/libraries/System.Drawing.Primitives/src/System/Drawing/Color.cs +++ b/src/libraries/System.Drawing.Primitives/src/System/Drawing/Color.cs @@ -565,21 +565,10 @@ namespace System.Drawing public KnownColor ToKnownColor() => (KnownColor)knownColor; - public override string ToString() - { - if (IsNamedColor) - { - return nameof(Color) + " [" + Name + "]"; - } - else if ((state & StateValueMask) != 0) - { - return nameof(Color) + " [A=" + A.ToString() + ", R=" + R.ToString() + ", G=" + G.ToString() + ", B=" + B.ToString() + "]"; - } - else - { - return nameof(Color) + " [Empty]"; - } - } + public override string ToString() => + IsNamedColor ? $"{nameof(Color)} [{Name}]": + (state & StateValueMask) != 0 ? $"{nameof(Color)} [A={A}, R={R}, G={G}, B={B}]" : + $"{nameof(Color)} [Empty]"; public static bool operator ==(Color left, Color right) => left.value == right.value diff --git a/src/libraries/System.Drawing.Primitives/src/System/Drawing/Point.cs b/src/libraries/System.Drawing.Primitives/src/System/Drawing/Point.cs index 36c56ce1d0c..678cecd313e 100644 --- a/src/libraries/System.Drawing.Primitives/src/System/Drawing/Point.cs +++ b/src/libraries/System.Drawing.Primitives/src/System/Drawing/Point.cs @@ -165,7 +165,7 @@ namespace System.Drawing /// /// Converts this to a human readable string. /// - public override readonly string ToString() => "{X=" + X.ToString() + ",Y=" + Y.ToString() + "}"; + public override readonly string ToString() => $"{{X={X},Y={Y}}}"; private static short HighInt16(int n) => unchecked((short)((n >> 16) & 0xffff)); diff --git a/src/libraries/System.Drawing.Primitives/src/System/Drawing/PointF.cs b/src/libraries/System.Drawing.Primitives/src/System/Drawing/PointF.cs index 47ae16677be..1a35a72826c 100644 --- a/src/libraries/System.Drawing.Primitives/src/System/Drawing/PointF.cs +++ b/src/libraries/System.Drawing.Primitives/src/System/Drawing/PointF.cs @@ -140,6 +140,6 @@ namespace System.Drawing public override readonly int GetHashCode() => HashCode.Combine(X.GetHashCode(), Y.GetHashCode()); - public override readonly string ToString() => "{X=" + x.ToString() + ", Y=" + y.ToString() + "}"; + public override readonly string ToString() => $"{{X={x}, Y={y}}}"; } } diff --git a/src/libraries/System.Drawing.Primitives/src/System/Drawing/Rectangle.cs b/src/libraries/System.Drawing.Primitives/src/System/Drawing/Rectangle.cs index 7d728a1fea5..e4f7500ced2 100644 --- a/src/libraries/System.Drawing.Primitives/src/System/Drawing/Rectangle.cs +++ b/src/libraries/System.Drawing.Primitives/src/System/Drawing/Rectangle.cs @@ -340,8 +340,6 @@ namespace System.Drawing /// /// Converts the attributes of this to a human readable string. /// - public override readonly string ToString() => - "{X=" + X.ToString() + ",Y=" + Y.ToString() + - ",Width=" + Width.ToString() + ",Height=" + Height.ToString() + "}"; + public override readonly string ToString() => $"{{X={X},Y={Y},Width={Width},Height={Height}}}"; } } diff --git a/src/libraries/System.Drawing.Primitives/src/System/Drawing/RectangleF.cs b/src/libraries/System.Drawing.Primitives/src/System/Drawing/RectangleF.cs index 508cd1252db..96f75808613 100644 --- a/src/libraries/System.Drawing.Primitives/src/System/Drawing/RectangleF.cs +++ b/src/libraries/System.Drawing.Primitives/src/System/Drawing/RectangleF.cs @@ -326,8 +326,6 @@ namespace System.Drawing /// Converts the and /// of this to a human-readable string. /// - public override readonly string ToString() => - "{X=" + X.ToString() + ",Y=" + Y.ToString() + - ",Width=" + Width.ToString() + ",Height=" + Height.ToString() + "}"; + public override readonly string ToString() => $"{{X={X},Y={Y},Width={Width},Height={Height}}}"; } } diff --git a/src/libraries/System.Drawing.Primitives/src/System/Drawing/Size.cs b/src/libraries/System.Drawing.Primitives/src/System/Drawing/Size.cs index bd140b7e080..c23a66d9142 100644 --- a/src/libraries/System.Drawing.Primitives/src/System/Drawing/Size.cs +++ b/src/libraries/System.Drawing.Primitives/src/System/Drawing/Size.cs @@ -189,7 +189,7 @@ namespace System.Drawing /// /// Creates a human-readable string that represents this . /// - public override readonly string ToString() => "{Width=" + width.ToString() + ", Height=" + height.ToString() + "}"; + public override readonly string ToString() => $"{{Width={width}, Height={height}}}"; /// /// Multiplies by an producing . diff --git a/src/libraries/System.Drawing.Primitives/src/System/Drawing/SizeF.cs b/src/libraries/System.Drawing.Primitives/src/System/Drawing/SizeF.cs index 4d0eb252dd6..d386f4dad85 100644 --- a/src/libraries/System.Drawing.Primitives/src/System/Drawing/SizeF.cs +++ b/src/libraries/System.Drawing.Primitives/src/System/Drawing/SizeF.cs @@ -177,7 +177,7 @@ namespace System.Drawing /// /// Creates a human-readable string that represents this . /// - public override readonly string ToString() => "{Width=" + width.ToString() + ", Height=" + height.ToString() + "}"; + public override readonly string ToString() => $"{{Width={width}, Height={height}}}"; /// /// Multiplies by a producing . diff --git a/src/libraries/System.Formats.Asn1/tests/Writer/WriteInteger.cs b/src/libraries/System.Formats.Asn1/tests/Writer/WriteInteger.cs index 29e2f2ce89c..938c758bd57 100644 --- a/src/libraries/System.Formats.Asn1/tests/Writer/WriteInteger.cs +++ b/src/libraries/System.Formats.Asn1/tests/Writer/WriteInteger.cs @@ -278,7 +278,7 @@ namespace System.Formats.Asn1.Tests.Writer [InlineData("FEFDFCFBFAF9F8F7F6F5F4F3F2F1F100")] public void VerifyWriteInteger_EncodedBytes(string valueHex) { - string expectedHex = "02" + (valueHex.Length / 2).ToString("X2") + valueHex; + string expectedHex = $"02{valueHex.Length / 2:X2}{valueHex}"; AsnWriter writer = new AsnWriter(AsnEncodingRules.BER); writer.WriteInteger(valueHex.HexToByteArray()); @@ -298,7 +298,7 @@ namespace System.Formats.Asn1.Tests.Writer [InlineData("FEFDFCFBFAF9F8F7F6F5F4F3F2F1F100")] public void VerifyWriteInteger_Context4_EncodedBytes(string valueHex) { - string expectedHex = "84" + (valueHex.Length / 2).ToString("X2") + valueHex; + string expectedHex = $"84{valueHex.Length / 2:X2}{valueHex}"; AsnWriter writer = new AsnWriter(AsnEncodingRules.BER); writer.WriteInteger(valueHex.HexToByteArray(), new Asn1Tag(TagClass.ContextSpecific, 4)); diff --git a/src/libraries/System.Globalization.Extensions/tests/Normalization/NormalizationAll.cs b/src/libraries/System.Globalization.Extensions/tests/Normalization/NormalizationAll.cs index 0f52f67c6b5..48f73a4527a 100644 --- a/src/libraries/System.Globalization.Extensions/tests/Normalization/NormalizationAll.cs +++ b/src/libraries/System.Globalization.Extensions/tests/Normalization/NormalizationAll.cs @@ -167,8 +167,7 @@ namespace System.Globalization.Tests StringBuilder sb = new StringBuilder(); for (int i=0; i()); _listOfAllDirs.Add(dirName); Directory.CreateDirectory(dirName); diff --git a/src/libraries/System.IO.Hashing/tests/NonCryptoHashTestDriver.cs b/src/libraries/System.IO.Hashing/tests/NonCryptoHashTestDriver.cs index 979e60a2806..3cec2c09836 100644 --- a/src/libraries/System.IO.Hashing/tests/NonCryptoHashTestDriver.cs +++ b/src/libraries/System.IO.Hashing/tests/NonCryptoHashTestDriver.cs @@ -331,7 +331,7 @@ namespace System.IO.Hashing.Tests foreach (byte b in input) { - builder.Append(b.ToString("X2")); + builder.Append($"{b:X2}"); } return builder.ToString(); diff --git a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorage.cs b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorage.cs index 170ce2feb97..1ad1801c270 100644 --- a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorage.cs +++ b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorage.cs @@ -153,7 +153,7 @@ namespace System.IO.IsolatedStorage if (Helper.IsDomain(scope)) { _domainIdentity = identity; - hash = $"{hash}{SeparatorExternal}{hash}"; + hash = string.Create(null, stackalloc char[128], $"{hash}{SeparatorExternal}{hash}"); } _assemblyIdentity = identity; diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs index 174b91bb219..389ab072d9a 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs @@ -174,7 +174,7 @@ namespace System.IO.MemoryMappedFiles Interop.Sys.MemoryMappedProtections protections, long capacity, HandleInheritability inheritability) { // The POSIX shared memory object name must begin with '/'. After that we just want something short and unique. - string mapName = "/corefx_map_" + Guid.NewGuid().ToString("N"); + string mapName = string.Create(null, stackalloc char[128], $"/corefx_map_{Guid.NewGuid():N}"); // Determine the flags to use when creating the shared memory object Interop.Sys.OpenFlags flags = (protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 ? diff --git a/src/libraries/System.IO.Pipelines/tests/Infrastructure/TestMemoryPool.cs b/src/libraries/System.IO.Pipelines/tests/Infrastructure/TestMemoryPool.cs index 9567b03e903..f990345a9bc 100644 --- a/src/libraries/System.IO.Pipelines/tests/Infrastructure/TestMemoryPool.cs +++ b/src/libraries/System.IO.Pipelines/tests/Infrastructure/TestMemoryPool.cs @@ -59,7 +59,7 @@ namespace System.IO.Pipelines ~PooledMemory() { - Debug.Assert(_returned, "Block being garbage collected instead of returned to pool" + Environment.NewLine + _leaser); + Debug.Assert(_returned, $"Block being garbage collected instead of returned to pool{Environment.NewLine}{_leaser}"); } protected override void Dispose(bool disposing) diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs index 39f47249a69..dc2180b39b7 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs @@ -156,7 +156,7 @@ namespace System.IO.Pipes private void CompleteCallback(int resultState) { - Debug.Assert(resultState == ResultSuccess || resultState == ResultError, "Unexpected result state " + resultState); + Debug.Assert(resultState == ResultSuccess || resultState == ResultError, $"Unexpected result state {resultState}"); CancellationToken cancellationToken = _cancellationRegistration.Token; ReleaseResources(); diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs index 0e46efe6998..85eb2f4eaf8 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs @@ -1005,7 +1005,7 @@ namespace System.IO.Ports if (count == 0) return 0; // return immediately if no bytes requested; no need for overhead. - Debug.Assert(timeout == SerialPort.InfiniteTimeout || timeout >= 0, "Serial Stream Read - called with timeout " + timeout); + Debug.Assert(timeout == SerialPort.InfiniteTimeout || timeout >= 0, $"Serial Stream Read - called with timeout {timeout}"); int numBytes = 0; if (_isAsync) @@ -1069,7 +1069,7 @@ namespace System.IO.Ports if (count == 0) return; // no need to expend overhead in creating asyncResult, etc. - Debug.Assert(timeout == SerialPort.InfiniteTimeout || timeout >= 0, "Serial Stream Write - write timeout is " + timeout); + Debug.Assert(timeout == SerialPort.InfiniteTimeout || timeout >= 0, $"Serial Stream Write - write timeout is {timeout}"); int numBytes; if (_isAsync) @@ -1627,7 +1627,7 @@ namespace System.IO.Ports // if we get IO pending, MSDN says we should wait on the WaitHandle, then call GetOverlappedResult // to get the results of WaitCommEvent. bool success = waitCommEventWaitHandle.WaitOne(); - Debug.Assert(success, "waitCommEventWaitHandle.WaitOne() returned error " + Marshal.GetLastWin32Error()); + Debug.Assert(success, $"waitCommEventWaitHandle.WaitOne() returned error {Marshal.GetLastWin32Error()}"); do { diff --git a/src/libraries/System.IO.Ports/tests/SerialPort/GetPortNames.cs b/src/libraries/System.IO.Ports/tests/SerialPort/GetPortNames.cs index 8376f729aa5..99be124701c 100644 --- a/src/libraries/System.IO.Ports/tests/SerialPort/GetPortNames.cs +++ b/src/libraries/System.IO.Ports/tests/SerialPort/GetPortNames.cs @@ -80,8 +80,8 @@ namespace System.IO.Ports.Tests get { var sb = new StringBuilder(); - sb.AppendLine("PortHelper Ports: " + string.Join(",", PortHelper.GetPorts())); - sb.AppendLine("SerialPort Ports: " + string.Join(",", SerialPort.GetPortNames())); + sb.AppendLine($"PortHelper Ports: {string.Join(",", PortHelper.GetPorts())}"); + sb.AppendLine($"SerialPort Ports: {string.Join(",", SerialPort.GetPortNames())}"); return sb.ToString(); } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs index 0c3ef9769ae..585d5901506 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/BranchLabel.cs @@ -20,10 +20,8 @@ namespace System.Linq.Expressions.Interpreter StackDepth = stackDepth; } - public override string ToString() - { - return string.Format(CultureInfo.InvariantCulture, "->{0} C({1}) S({2})", Index, ContinuationStackDepth, StackDepth); - } + public override string ToString() => + string.Create(CultureInfo.InvariantCulture, $"->{Index} C({ContinuationStackDepth}) S({StackDepth})"); } internal sealed class BranchLabel diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs index 0fbabd6289f..cf1f973204a 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs @@ -195,7 +195,7 @@ namespace System.Linq.Expressions.Interpreter instruction.ConsumedContinuations >= 0 && instruction.ProducedContinuations >= 0, "bad instruction " + instruction.ToString()); _currentStackDepth -= instruction.ConsumedStack; - Debug.Assert(_currentStackDepth >= 0, "negative stack depth " + instruction.ToString()); + Debug.Assert(_currentStackDepth >= 0, $"negative stack depth {instruction}"); _currentStackDepth += instruction.ProducedStack; if (_currentStackDepth > _maxStackDepth) { @@ -203,7 +203,7 @@ namespace System.Linq.Expressions.Interpreter } _currentContinuationsDepth -= instruction.ConsumedContinuations; - Debug.Assert(_currentContinuationsDepth >= 0, "negative continuations " + instruction.ToString()); + Debug.Assert(_currentContinuationsDepth >= 0, $"negative continuations {instruction}"); _currentContinuationsDepth += instruction.ProducedContinuations; if (_currentContinuationsDepth > _maxContinuationDepth) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs index 784baac2de9..b5753f67732 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs @@ -51,7 +51,7 @@ namespace System.Linq.Expressions.Interpreter public bool Matches(Type exceptionType) => _exceptionType.IsAssignableFrom(exceptionType); public override string ToString() => - string.Format(CultureInfo.InvariantCulture, "catch ({0}) [{1}->{2}]", _exceptionType.Name, HandlerStartIndex, HandlerEndIndex); + string.Create(CultureInfo.InvariantCulture, $"catch ({_exceptionType.Name}) [{HandlerStartIndex}->{HandlerEndIndex}]"); } internal sealed class TryCatchFinallyHandler @@ -251,11 +251,11 @@ namespace System.Linq.Expressions.Interpreter { if (IsClear) { - return string.Format(CultureInfo.InvariantCulture, "{0}: clear", Index); + return string.Create(CultureInfo.InvariantCulture, $"{Index}: clear"); } else { - return string.Format(CultureInfo.InvariantCulture, "{0}: [{1}-{2}] '{3}'", Index, StartLine, EndLine, FileName); + return string.Create(CultureInfo.InvariantCulture, $"{Index}: [{StartLine}-{EndLine}] '{FileName}'"); } } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs index 3956e67b29a..77b399b366d 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs @@ -167,7 +167,7 @@ namespace System.Linq.Expressions.Interpreter InstructionList.DebugView.InstructionView instructionView = instructionViews[i]; - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}IP_{1}: {2}", _indent, i.ToString().PadLeft(4, '0'), instructionView.GetValue()).AppendLine(); + sb.AppendLine(CultureInfo.InvariantCulture, $"{_indent}IP_{i.ToString().PadLeft(4, '0')}: {instructionView.GetValue()}"); } EmitExits(sb, instructions.Length); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs index 83177991b77..d078d82a597 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LocalVariables.cs @@ -40,10 +40,8 @@ namespace System.Linq.Expressions.Interpreter _flags = (closure ? InClosureFlag : 0); } - public override string ToString() - { - return string.Format(CultureInfo.InvariantCulture, "{0}: {1} {2}", Index, IsBoxed ? "boxed" : null, InClosure ? "in closure" : null); - } + public override string ToString() => + string.Create(CultureInfo.InvariantCulture, $"{Index}: {(IsBoxed ? "boxed" : null)} {(InClosure ? "in closure" : null)}"); } internal readonly struct LocalDefinition diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/StackOperations.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/StackOperations.cs index 0a3586ed514..53e3fa831e1 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/StackOperations.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/StackOperations.cs @@ -45,10 +45,8 @@ namespace System.Linq.Expressions.Interpreter return 1; } - public override string ToDebugString(int instructionIndex, object? cookie, Func labelIndexer, IReadOnlyList? objects) - { - return string.Format(CultureInfo.InvariantCulture, "LoadCached({0}: {1})", _index, objects![(int)_index]); - } + public override string ToDebugString(int instructionIndex, object? cookie, Func labelIndexer, IReadOnlyList? objects) => + string.Create(CultureInfo.InvariantCulture, $"LoadCached({_index}: {objects![(int)_index]})"); public override string ToString() => "LoadCached(" + _index + ")"; } diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs index 93595b1d12a..40275b5c8d7 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestState.cs @@ -175,7 +175,7 @@ namespace System.Net.Http #if DEBUG Interlocked.Increment(ref s_dbg_callDispose); #endif - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"GCHandle=0x{ToIntPtr().ToString("X")}, disposed={_disposed}, disposing={disposing}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"GCHandle=0x{ToIntPtr():X}, disposed={_disposed}, disposing={disposing}"); // Since there is no finalizer and this class is sealed, the disposing parameter should be TRUE. Debug.Assert(disposing, "WinHttpRequestState.Dispose() should have disposing=TRUE"); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpTraceHelper.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpTraceHelper.cs index 104808b472a..e039d50dad1 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpTraceHelper.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpTraceHelper.cs @@ -15,7 +15,7 @@ namespace System.Net.Http NetEventSource.Info( thisOrContextObject, - $"handle=0x{handle.ToString("X")}, context=0x{context.ToString("X")}, {GetStringFromInternetStatus(status)}", + $"handle=0x{handle:X}, context=0x{context:X}, {GetStringFromInternetStatus(status)}", memberName); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderValue.cs index ce534b0e1d5..f04f569b725 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AltSvcHeaderValue.cs @@ -56,13 +56,12 @@ namespace System.Net.Http.Headers sb.Append("=\""); if (Host != null) sb.Append(Host); sb.Append(':'); - sb.Append(Port.ToString(CultureInfo.InvariantCulture)); + sb.Append((uint)Port); sb.Append('"'); if (MaxAge != TimeSpan.FromTicks(AltSvcHeaderParser.DefaultMaxAgeTicks)) { - sb.Append("; ma="); - sb.Append((MaxAge.Ticks / TimeSpan.TicksPerSecond).ToString(CultureInfo.InvariantCulture)); + sb.Append(CultureInfo.InvariantCulture, $"; ma={MaxAge.Ticks / TimeSpan.TicksPerSecond}"); } if (Persist) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs index b38c3396ca9..e8186404aa4 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs @@ -205,7 +205,7 @@ namespace System.Net.Http.Headers { // In the corner case where the value is negative, ensure it uses // the invariant's negative sign rather than the current culture's. - sb.Append(maxAge.ToString(NumberFormatInfo.InvariantInfo)); + sb.Append(NumberFormatInfo.InvariantInfo, $"{maxAge}"); } } @@ -222,7 +222,7 @@ namespace System.Net.Http.Headers { // In the corner case where the value is negative, ensure it uses // the invariant's negative sign rather than the current culture's. - sb.Append(sharedMaxAge.ToString(NumberFormatInfo.InvariantInfo)); + sb.Append(NumberFormatInfo.InvariantInfo, $"{sharedMaxAge}"); } } @@ -241,7 +241,7 @@ namespace System.Net.Http.Headers { // In the corner case where the value is negative, ensure it uses // the invariant's negative sign rather than the current culture's. - sb.Append(maxStaleLimit.ToString(NumberFormatInfo.InvariantInfo)); + sb.Append(NumberFormatInfo.InvariantInfo, $"{maxStaleLimit}"); } } } @@ -259,7 +259,7 @@ namespace System.Net.Http.Headers { // In the corner case where the value is negative, ensure it uses // the invariant's negative sign rather than the current culture's. - sb.Append(minFresh.ToString(NumberFormatInfo.InvariantInfo)); + sb.Append(NumberFormatInfo.InvariantInfo, $"{minFresh}"); } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs index fd1074f16f9..d52a92875a6 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs @@ -449,7 +449,7 @@ namespace System.Net.Http.Headers if (info.IsEmpty) { bool headerRemoved = Remove(descriptor); - Debug.Assert(headerRemoved, "Existing header '" + descriptor.Name + "' couldn't be removed."); + Debug.Assert(headerRemoved, $"Existing header '{descriptor.Name}' couldn't be removed."); } return result; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs index cba711f89a2..91262983d8c 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs @@ -56,17 +56,20 @@ namespace System.Net.Http.Headers public override string ToString() { + Span stackBuffer = stackalloc char[128]; + if (!_from.HasValue) { Debug.Assert(_to != null); - return "-" + _to.Value.ToString(NumberFormatInfo.InvariantInfo); + return string.Create(CultureInfo.InvariantCulture, stackBuffer, $"-{_to.Value}"); } - else if (!_to.HasValue) + + if (!_to.HasValue) { - return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-"; + return string.Create(CultureInfo.InvariantCulture, stackBuffer, $"{_from.Value}-"); ; } - return _from.Value.ToString(NumberFormatInfo.InvariantInfo) + "-" + - _to.Value.ToString(NumberFormatInfo.InvariantInfo); + + return string.Create(CultureInfo.InvariantCulture, stackBuffer, $"{_from.Value}-{_to.Value}"); } public override bool Equals([NotNullWhen(true)] object? obj) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/StringWithQualityHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/StringWithQualityHeaderValue.cs index 814a053f5ad..377a2113dfa 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/StringWithQualityHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/StringWithQualityHeaderValue.cs @@ -54,7 +54,7 @@ namespace System.Net.Http.Headers { if (_quality.HasValue) { - return _value + "; q=" + _quality.Value.ToString("0.0##", NumberFormatInfo.InvariantInfo); + return string.Create(CultureInfo.InvariantCulture, stackalloc char[128], $"{_value}; q={_quality.Value:0.0##}"); } return _value; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs index c232ba8371d..caa70684ec7 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs @@ -74,7 +74,7 @@ namespace System.Net.Http.Headers StringBuilder sb = StringBuilderCache.Acquire(); // Warning codes are always 3 digits according to RFC2616 - sb.Append(_code.ToString("000", NumberFormatInfo.InvariantInfo)); + sb.Append(NumberFormatInfo.InvariantInfo, $"{_code:000}"); sb.Append(' '); sb.Append(_agent); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs index afb7082a57a..eabc0efe68e 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs @@ -80,35 +80,31 @@ namespace System.Net.Http Debug.Assert(preamble != null); Debug.Assert(codePage == encoding.CodePage, - "Encoding code page mismatch for encoding: " + encoding.EncodingName, - "Expected (constant): {0}, Actual (Encoding.CodePage): {1}", codePage, encoding.CodePage); + $"Encoding code page mismatch for encoding: {encoding.EncodingName}", + $"Expected (constant): {codePage}, Actual (Encoding.CodePage): {encoding.CodePage}"); byte[] actualPreamble = encoding.GetPreamble(); Debug.Assert(preambleLength == actualPreamble.Length, - "Encoding preamble length mismatch for encoding: " + encoding.EncodingName, - "Expected (constant): {0}, Actual (Encoding.GetPreamble().Length): {1}", preambleLength, actualPreamble.Length); + $"Encoding preamble length mismatch for encoding: {encoding.EncodingName}", + $"Expected (constant): {preambleLength}, Actual (Encoding.GetPreamble().Length): {actualPreamble.Length}"); Debug.Assert(actualPreamble.Length >= 2); int actualFirst2Bytes = actualPreamble[0] << 8 | actualPreamble[1]; Debug.Assert(first2Bytes == actualFirst2Bytes, - "Encoding preamble first 2 bytes mismatch for encoding: " + encoding.EncodingName, - "Expected (constant): {0}, Actual: {1}", first2Bytes, actualFirst2Bytes); + $"Encoding preamble first 2 bytes mismatch for encoding: {encoding.EncodingName}", + $"Expected (constant): {first2Bytes}, Actual: {actualFirst2Bytes}"); Debug.Assert(preamble.Length == actualPreamble.Length, - "Encoding preamble mismatch for encoding: " + encoding.EncodingName, - "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", - BitConverter.ToString(preamble), - BitConverter.ToString(actualPreamble)); + $"Encoding preamble mismatch for encoding: {encoding.EncodingName}", + $"Expected (constant): {BitConverter.ToString(preamble)}, Actual (Encoding.GetPreamble()): {BitConverter.ToString(actualPreamble)}"); for (int i = 0; i < preamble.Length; i++) { Debug.Assert(preamble[i] == actualPreamble[i], - "Encoding preamble mismatch for encoding: " + encoding.EncodingName, - "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", - BitConverter.ToString(preamble), - BitConverter.ToString(actualPreamble)); + $"Encoding preamble mismatch for encoding: {encoding.EncodingName}", + $"Expected (constant): {BitConverter.ToString(preamble)}, Actual (Encoding.GetPreamble()): {BitConverter.ToString(actualPreamble)}"); } } #endif diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.NtAuth.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.NtAuth.cs index 74abe97e80d..e9468042f64 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.NtAuth.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.NtAuth.cs @@ -108,7 +108,7 @@ namespace System.Net.Http if (!isProxyAuth && !authUri.IsDefaultPort) { - hostName = $"{hostName}:{authUri.Port}"; + hostName = string.Create(null, stackalloc char[128], $"{hostName}:{authUri.Port}"); } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs index ce4f3e74169..4667b7bec32 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs @@ -9,6 +9,7 @@ using System.Net.Quic; using System.IO; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.Net.Http.Headers; using System.Net.Security; @@ -78,7 +79,7 @@ namespace System.Net.Http _connection = connection; bool altUsedDefaultPort = pool.Kind == HttpConnectionKind.Http && authority.Port == HttpConnectionPool.DefaultHttpPort || pool.Kind == HttpConnectionKind.Https && authority.Port == HttpConnectionPool.DefaultHttpsPort; - string altUsedValue = altUsedDefaultPort ? authority.IdnHost : authority.IdnHost + ":" + authority.Port.ToString(Globalization.CultureInfo.InvariantCulture); + string altUsedValue = altUsedDefaultPort ? authority.IdnHost : string.Create(CultureInfo.InvariantCulture, $"{authority.IdnHost}:{authority.Port}"); _altUsedEncodedHeader = QPack.QPackEncoder.EncodeLiteralHeaderFieldWithoutNameReferenceToArray(KnownHeaders.AltUsed.Name, altUsedValue); // Errors are observed via Abort(). diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs index 00a1a376799..e84f21dce3b 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs @@ -349,15 +349,12 @@ namespace System.Net.Http var sb = new StringBuilder(); Debug.Assert(_originAuthority != null); - sb - .Append(IsSecure ? "https://" : "http://") - .Append(_originAuthority.IdnHost); + sb.Append(IsSecure ? "https://" : "http://") + .Append(_originAuthority.IdnHost); if (_originAuthority.Port != (IsSecure ? DefaultHttpsPort : DefaultHttpPort)) { - sb - .Append(':') - .Append(_originAuthority.Port.ToString(CultureInfo.InvariantCulture)); + sb.Append(CultureInfo.InvariantCulture, $":{_originAuthority.Port}"); } _http2AltSvcOriginUri = Encoding.ASCII.GetBytes(sb.ToString()); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerException.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerException.cs index 968adb53345..249e579d47d 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerException.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerException.cs @@ -13,23 +13,23 @@ namespace System.Net { public HttpListenerException() : base(Marshal.GetLastPInvokeError()) { - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, NativeErrorCode.ToString() + ":" + Message); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"{NativeErrorCode}:{Message}"); } public HttpListenerException(int errorCode) : base(errorCode) { - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, NativeErrorCode.ToString() + ":" + Message); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"{NativeErrorCode}:{Message}"); } public HttpListenerException(int errorCode, string message) : base(errorCode, message) { - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, NativeErrorCode.ToString() + ":" + Message); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"{NativeErrorCode}:{Message}"); } protected HttpListenerException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, NativeErrorCode.ToString() + ":" + Message); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"{NativeErrorCode}:{Message}"); } // the base class returns the HResult with this property diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs index 61f05ac248e..f078b5bdbee 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs @@ -119,8 +119,7 @@ namespace System.Net private static Encoding GetEncoding(EncodingType type) { - Debug.Assert((type == EncodingType.Primary) || (type == EncodingType.Secondary), - "Unknown 'EncodingType' value: " + type.ToString()); + Debug.Assert((type == EncodingType.Primary) || (type == EncodingType.Secondary), $"Unknown 'EncodingType' value: {type}"); if (type == EncodingType.Secondary) { @@ -330,8 +329,7 @@ namespace System.Net { foreach (byte octet in octets) { - target.Append('%'); - target.Append(octet.ToString("X2", CultureInfo.InvariantCulture)); + target.Append($"%{octet:X2}"); } } @@ -350,7 +348,7 @@ namespace System.Net { octetString.Append(' '); } - octetString.Append(octet.ToString("X2", CultureInfo.InvariantCulture)); + octetString.Append($"{octet:X2}"); } return octetString.ToString(); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs index 13562495cb4..63c96497909 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs @@ -962,7 +962,7 @@ namespace System.Net if (NetEventSource.Log.IsEnabled()) { NetEventSource.Info(this, - $"HandleAuthentication creating new WindowsIdentity from user context: {userContext.DangerousGetHandle().ToString("x8")}"); + $"HandleAuthentication creating new WindowsIdentity from user context: {userContext.DangerousGetHandle():x8}"); } WindowsPrincipal windowsPrincipal = new WindowsPrincipal( @@ -1881,7 +1881,7 @@ namespace System.Net private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode: {errorCode}, numBytes: {numBytes}, nativeOverlapped: {((IntPtr)nativeOverlapped).ToString("x")}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode: {errorCode}, numBytes: {numBytes}, nativeOverlapped: {(IntPtr)nativeOverlapped:x}"); // take the DisconnectAsyncResult object from the state DisconnectAsyncResult asyncResult = (DisconnectAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; IOCompleted(asyncResult, errorCode, numBytes, nativeOverlapped); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs index 3eadb3cf7e5..ecbadd5943c 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs @@ -306,7 +306,7 @@ namespace System.Net private static void IOCompleted(HttpRequestStreamAsyncResult asyncResult, uint errorCode, uint numBytes) { - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode:x8} numBytes: {numBytes}"); object? result = null; try { @@ -333,7 +333,7 @@ namespace System.Net { HttpRequestStreamAsyncResult asyncResult = (HttpRequestStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes} nativeOverlapped:0x {((IntPtr)nativeOverlapped).ToString("x8")}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode:x8} numBytes: {numBytes} nativeOverlapped:0x{(IntPtr)nativeOverlapped:x8}"); IOCompleted(asyncResult, errorCode, numBytes); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs index 5a41b0ddeed..d41ff445938 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs @@ -185,7 +185,7 @@ namespace System.Net private static void IOCompleted(HttpResponseStreamAsyncResult asyncResult, uint errorCode, uint numBytes) { - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode:0x{errorCode:x8} numBytes: {numBytes}"); object? result = null; try { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs index b36252e9de8..0b57602b1b7 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs @@ -106,7 +106,7 @@ namespace System.Net while (true) { Debug.Assert(_requestContext != null); - if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Calling Interop.HttpApi.HttpReceiveHttpRequest RequestId: {_requestContext.RequestBlob->RequestId}Buffer:0x {((IntPtr)_requestContext.RequestBlob).ToString("x")} Size: {_requestContext.Size}"); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Calling Interop.HttpApi.HttpReceiveHttpRequest RequestId: {_requestContext.RequestBlob->RequestId} Buffer: 0x{(IntPtr)_requestContext.RequestBlob:x} Size: {_requestContext.Size}"); uint bytesTransferred = 0; Debug.Assert(AsyncObject != null); HttpListenerSession listenerSession = (HttpListenerSession)AsyncObject!; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs index ee844910e4d..9b9c501746d 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs @@ -137,15 +137,6 @@ namespace System.Net.WebSockets return webSocketContext; } - internal static string GetTraceMsgForParameters(int offset, int count, CancellationToken cancellationToken) - { - return string.Format(CultureInfo.InvariantCulture, - "offset: {0}, count: {1}, cancellationToken.CanBeCanceled: {2}", - offset, - count, - cancellationToken.CanBeCanceled); - } - internal static ConfiguredTaskAwaitable SuppressContextFlow(this Task task) { // We don't flow the synchronization context within WebSocket.xxxAsync - but the calling application diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs index 84d4222f8cd..9355cd36ccb 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs @@ -63,20 +63,6 @@ namespace System.Net.WebSockets HttpWebSocket.ValidateOptions(subProtocol, internalBuffer.ReceiveBufferSize, internalBuffer.SendBufferSize, keepAliveInterval); - string parameters = string.Empty; - - if (NetEventSource.Log.IsEnabled()) - { - parameters = string.Format(CultureInfo.InvariantCulture, - "ReceiveBufferSize: {0}, SendBufferSize: {1}, Protocols: {2}, KeepAliveInterval: {3}, innerStream: {4}, internalBuffer: {5}", - internalBuffer.ReceiveBufferSize, - internalBuffer.SendBufferSize, - subProtocol, - keepAliveInterval, - NetEventSource.GetHashCode(innerStream), - NetEventSource.GetHashCode(internalBuffer)); - } - _thisLock = new object(); _innerStream = innerStream; @@ -251,15 +237,6 @@ namespace System.Net.WebSockets "'messageType' MUST be either 'WebSocketMessageType.Binary' or 'WebSocketMessageType.Text'."); Debug.Assert(buffer.Array != null); - string inputParameter = string.Empty; - if (NetEventSource.Log.IsEnabled()) - { - inputParameter = string.Format(CultureInfo.InvariantCulture, - "messageType: {0}, endOfMessage: {1}", - messageType, - endOfMessage); - } - ThrowIfPendingException(); ThrowIfDisposed(); ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseReceived); @@ -421,15 +398,6 @@ namespace System.Net.WebSockets string statusDescription, CancellationToken cancellationToken) { - string inputParameter = string.Empty; - if (NetEventSource.Log.IsEnabled()) - { - inputParameter = string.Format(CultureInfo.InvariantCulture, - "closeStatus: {0}, statusDescription: {1}", - closeStatus, - statusDescription); - } - ThrowIfPendingException(); if (IsStateTerminal(State)) { @@ -648,15 +616,6 @@ namespace System.Net.WebSockets string? statusDescription, CancellationToken cancellationToken) { - string inputParameter = string.Empty; - if (NetEventSource.Log.IsEnabled()) - { - inputParameter = string.Format(CultureInfo.InvariantCulture, - "closeStatus: {0}, statusDescription: {1}", - closeStatus, - statusDescription); - } - ThrowIfPendingException(); if (IsStateTerminal(State)) { @@ -1067,15 +1026,7 @@ namespace System.Net.WebSockets // This indicates a contract violation of the websocket protocol component, // because we currently don't support any WebSocket extensions and would // not accept a Websocket handshake requesting extensions - Debug.Fail(string.Format(CultureInfo.InvariantCulture, - "The value of 'bufferType' ({0}) is invalid. Valid buffer types: {1}, {2}, {3}, {4}, {5}.", - bufferType, - WebSocketProtocolComponent.BufferType.Close, - WebSocketProtocolComponent.BufferType.BinaryFragment, - WebSocketProtocolComponent.BufferType.BinaryMessage, - WebSocketProtocolComponent.BufferType.UTF8Fragment, - WebSocketProtocolComponent.BufferType.UTF8Message)); - + Debug.Fail($"The value of 'bufferType' ({bufferType}) is invalid."); throw new WebSocketException(WebSocketError.NativeError, SR.Format(SR.net_WebSockets_InvalidBufferType, bufferType, @@ -1337,14 +1288,7 @@ namespace System.Net.WebSockets _closeStatus = closeStatus; _closeStatusDescription = closeStatusDescription; - if (NetEventSource.Log.IsEnabled()) - { - string parameters = string.Format(CultureInfo.InvariantCulture, - "closeStatus: {0}, closeStatusDescription: {1}, _State: {2}", - closeStatus, closeStatusDescription, _state); - - NetEventSource.Info(this, parameters); - } + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"closeStatus: {closeStatus}, closeStatusDescription: {closeStatusDescription}, _State: {_state}"); } private static async void OnKeepAlive(object? sender) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs index 838963d98d8..712b0d7f39d 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs @@ -49,14 +49,10 @@ namespace System.Net.WebSockets private WebSocketBuffer(ArraySegment internalBuffer, int receiveBufferSize, int sendBufferSize) { Debug.Assert(internalBuffer.Array != null, "'internalBuffer.Array' MUST NOT be NULL."); - Debug.Assert(receiveBufferSize >= HttpWebSocket.MinReceiveBufferSize, - "'receiveBufferSize' MUST be at least " + HttpWebSocket.MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); - Debug.Assert(sendBufferSize >= HttpWebSocket.MinSendBufferSize, - "'sendBufferSize' MUST be at least " + HttpWebSocket.MinSendBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); - Debug.Assert(receiveBufferSize <= HttpWebSocket.MaxBufferSize, - "'receiveBufferSize' MUST NOT exceed " + HttpWebSocket.MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); - Debug.Assert(sendBufferSize <= HttpWebSocket.MaxBufferSize, - "'sendBufferSize' MUST NOT exceed " + HttpWebSocket.MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); + Debug.Assert(receiveBufferSize >= HttpWebSocket.MinReceiveBufferSize, $"'receiveBufferSize' MUST be at least {HttpWebSocket.MinReceiveBufferSize}."); + Debug.Assert(sendBufferSize >= HttpWebSocket.MinSendBufferSize, $"'sendBufferSize' MUST be at least {HttpWebSocket.MinSendBufferSize}."); + Debug.Assert(receiveBufferSize <= HttpWebSocket.MaxBufferSize, $"'receiveBufferSize' MUST NOT exceed {HttpWebSocket.MaxBufferSize}."); + Debug.Assert(sendBufferSize <= HttpWebSocket.MaxBufferSize, $"'sendBufferSize' MUST NOT exceed {HttpWebSocket.MaxBufferSize}."); _receiveBufferSize = receiveBufferSize; _sendBufferSize = sendBufferSize; @@ -634,10 +630,8 @@ namespace System.Net.WebSockets internal static ArraySegment CreateInternalBufferArraySegment(int receiveBufferSize, int sendBufferSize, bool isServerBuffer) { - Debug.Assert(receiveBufferSize >= HttpWebSocket.MinReceiveBufferSize, - "'receiveBufferSize' MUST be at least " + HttpWebSocket.MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); - Debug.Assert(sendBufferSize >= HttpWebSocket.MinSendBufferSize, - "'sendBufferSize' MUST be at least " + HttpWebSocket.MinSendBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); + Debug.Assert(receiveBufferSize >= HttpWebSocket.MinReceiveBufferSize, $"'receiveBufferSize' MUST be at least {HttpWebSocket.MinReceiveBufferSize}."); + Debug.Assert(sendBufferSize >= HttpWebSocket.MinSendBufferSize, $"'sendBufferSize' MUST be at least {HttpWebSocket.MinSendBufferSize}."); int internalBufferSize = GetInternalBufferSize(receiveBufferSize, sendBufferSize, isServerBuffer); return new ArraySegment(new byte[internalBufferSize]); @@ -645,10 +639,8 @@ namespace System.Net.WebSockets internal static void Validate(int count, int receiveBufferSize, int sendBufferSize, bool isServerBuffer) { - Debug.Assert(receiveBufferSize >= HttpWebSocket.MinReceiveBufferSize, - "'receiveBufferSize' MUST be at least " + HttpWebSocket.MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); - Debug.Assert(sendBufferSize >= HttpWebSocket.MinSendBufferSize, - "'sendBufferSize' MUST be at least " + HttpWebSocket.MinSendBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); + Debug.Assert(receiveBufferSize >= HttpWebSocket.MinReceiveBufferSize, $"'receiveBufferSize' MUST be at least {HttpWebSocket.MinReceiveBufferSize}."); + Debug.Assert(sendBufferSize >= HttpWebSocket.MinSendBufferSize, $"'sendBufferSize' MUST be at least {HttpWebSocket.MinSendBufferSize}."); int minBufferSize = GetInternalBufferSize(receiveBufferSize, sendBufferSize, isServerBuffer); if (count < minBufferSize) @@ -660,15 +652,11 @@ namespace System.Net.WebSockets private static int GetInternalBufferSize(int receiveBufferSize, int sendBufferSize, bool isServerBuffer) { - Debug.Assert(receiveBufferSize >= HttpWebSocket.MinReceiveBufferSize, - "'receiveBufferSize' MUST be at least " + HttpWebSocket.MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); - Debug.Assert(sendBufferSize >= HttpWebSocket.MinSendBufferSize, - "'sendBufferSize' MUST be at least " + HttpWebSocket.MinSendBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); + Debug.Assert(receiveBufferSize >= HttpWebSocket.MinReceiveBufferSize, $"'receiveBufferSize' MUST be at least {HttpWebSocket.MinReceiveBufferSize}."); + Debug.Assert(sendBufferSize >= HttpWebSocket.MinSendBufferSize, $"'sendBufferSize' MUST be at least {HttpWebSocket.MinSendBufferSize}."); - Debug.Assert(receiveBufferSize <= HttpWebSocket.MaxBufferSize, - "'receiveBufferSize' MUST be less than or equal to " + HttpWebSocket.MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); - Debug.Assert(sendBufferSize <= HttpWebSocket.MaxBufferSize, - "'sendBufferSize' MUST be at less than or equal to " + HttpWebSocket.MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + "."); + Debug.Assert(receiveBufferSize <= HttpWebSocket.MaxBufferSize, $"'receiveBufferSize' MUST be less than or equal to {HttpWebSocket.MaxBufferSize}."); + Debug.Assert(sendBufferSize <= HttpWebSocket.MaxBufferSize, $"'sendBufferSize' MUST be at less than or equal to {HttpWebSocket.MaxBufferSize}."); int nativeSendBufferSize = GetNativeSendBufferSize(sendBufferSize, isServerBuffer); return 2 * receiveBufferSize + nativeSendBufferSize + NativeOverheadBufferSize + s_PropertyBufferSize; diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/DomainLiteralReader.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/DomainLiteralReader.cs index 29a31a1fc4c..2f03cf45b45 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/DomainLiteralReader.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/DomainLiteralReader.cs @@ -30,7 +30,7 @@ namespace System.Net.Mail // internal static bool TryReadReverse(string data, int index, out int outIndex, bool throwExceptionIfFail) { - Debug.Assert(0 <= index && index < data.Length, "index was outside the bounds of the string: " + index); + Debug.Assert(0 <= index && index < data.Length, $"index was outside the bounds of the string: {index}"); Debug.Assert(data[index] == MailBnfHelper.EndSquareBracket, "data did not end with a square bracket"); // Skip the end bracket diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/DotAtomReader.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/DotAtomReader.cs index f3a1da7361b..f50b9946f4f 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/DotAtomReader.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/DotAtomReader.cs @@ -36,7 +36,7 @@ namespace System.Net.Mail // internal static bool TryReadReverse(string data, int index, out int outIndex, bool throwExceptionIfFail) { - Debug.Assert(0 <= index && index < data.Length, "index was outside the bounds of the string: " + index); + Debug.Assert(0 <= index && index < data.Length, $"index was outside the bounds of the string: {index}"); int startIndex = index; diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddressParser.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddressParser.cs index 38867b921b9..fe57dd93c14 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddressParser.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddressParser.cs @@ -27,7 +27,7 @@ namespace System.Net.Mail { int index = data.Length - 1; bool parseSuccess = TryParseAddress(data, false, ref index, out parsedAddress, throwExceptionIfFail); - Debug.Assert(!parseSuccess || index == -1, "The index indicates that part of the address was not parsed: " + index); + Debug.Assert(!parseSuccess || index == -1, $"The index indicates that part of the address was not parsed: {index}"); return parseSuccess; } @@ -66,7 +66,7 @@ namespace System.Net.Mail private static bool TryParseAddress(string data, bool expectMultipleAddresses, ref int index, out ParseAddressInfo parseAddressInfo, bool throwExceptionIfFail) { Debug.Assert(!string.IsNullOrEmpty(data)); - Debug.Assert(index >= 0 && index < data.Length, "Index out of range: " + index + ", " + data.Length); + Debug.Assert(index >= 0 && index < data.Length, $"Index out of range: {index}, {data.Length}"); // Parsed components to be assembled as a MailAddress later string? displayName; @@ -378,7 +378,7 @@ namespace System.Net.Mail return false; } - Debug.Assert(data[index + 1] == MailBnfHelper.Quote, "Mis-aligned index: " + index); + Debug.Assert(data[index + 1] == MailBnfHelper.Quote, $"Mis-aligned index: {index}"); // Do not include the bounding quotes on the display name int leftIndex = index + 2; @@ -417,7 +417,7 @@ namespace System.Net.Mail return false; } - Debug.Assert(index < 0 || data[index] == MailBnfHelper.Comma, "Mis-aligned index: " + index); + Debug.Assert(index < 0 || data[index] == MailBnfHelper.Comma, $"Mis-aligned index: {index}"); // Do not include the Comma (if any), and because there were no bounding quotes, // trim extra whitespace. diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/QuotedPairReader.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/QuotedPairReader.cs index e98a031e77c..34079edf51c 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/QuotedPairReader.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/QuotedPairReader.cs @@ -33,7 +33,7 @@ namespace System.Net.Mail // Throws a FormatException or false is returned if the an escaped Unicode character is found but was not permitted. internal static bool TryCountQuotedChars(string data, int index, bool permitUnicodeEscaping, out int outIndex, bool throwExceptionIfFail) { - Debug.Assert(0 <= index && index < data.Length, "Index out of range: " + index + ", " + data.Length); + Debug.Assert(0 <= index && index < data.Length, $"Index out of range: {index}, {data.Length}"); if (index <= 0 || data[index - 1] != MailBnfHelper.Backslash) { @@ -81,7 +81,7 @@ namespace System.Net.Mail // Return value: The number of consecutive backslashes, including the initial one at data[index]. private static int CountBackslashes(string data, int index) { - Debug.Assert(index >= 0 && data[index] == MailBnfHelper.Backslash, "index was not a backslash: " + index); + Debug.Assert(index >= 0 && data[index] == MailBnfHelper.Backslash, $"index was not a backslash: {index}"); // Find all the backslashes. It's possible that there are multiple escaped/quoted backslashes. int backslashCount = 0; @@ -92,7 +92,7 @@ namespace System.Net.Mail } while (index >= 0 && data[index] == MailBnfHelper.Backslash); // At this point data[index] should not be a backslash - Debug.Assert(index < 0 || data[index] != MailBnfHelper.Backslash, "index was a backslash: " + index); + Debug.Assert(index < 0 || data[index] != MailBnfHelper.Backslash, $"index was a backslash: {index}"); return backslashCount; } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/QuotedStringFormatReader.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/QuotedStringFormatReader.cs index c62b7f83500..e12d7316400 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/QuotedStringFormatReader.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/QuotedStringFormatReader.cs @@ -34,9 +34,9 @@ namespace System.Net.Mail // internal static bool TryReadReverseQuoted(string data, int index, bool permitUnicode, out int outIndex, bool throwExceptionIfFail) { - Debug.Assert(0 <= index && index < data.Length, "Index out of range: " + index + ", " + data.Length); + Debug.Assert(0 <= index && index < data.Length, $"Index out of range: {index}, {data.Length}"); // Check for the first bounding quote - Debug.Assert(data[index] == MailBnfHelper.Quote, "Initial char at index " + index + " was not a quote."); + Debug.Assert(data[index] == MailBnfHelper.Quote, $"Initial char at index {index} was not a quote."); // Skip the bounding quote index--; @@ -125,7 +125,7 @@ namespace System.Net.Mail // internal static bool TryReadReverseUnQuoted(string data, int index, bool permitUnicode, bool expectCommaDelimiter, out int outIndex, bool throwExceptionIfFail) { - Debug.Assert(0 <= index && index < data.Length, "Index out of range: " + index + ", " + data.Length); + Debug.Assert(0 <= index && index < data.Length, $"Index out of range: {index}, {data.Length}"); do { diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs index cceff5d15fa..415c1e6e972 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs @@ -393,7 +393,7 @@ namespace System.Net.Mail string pathAndFilename; while (true) { - filename = Guid.NewGuid().ToString() + ".eml"; + filename = $"{Guid.NewGuid()}.eml"; pathAndFilename = Path.Combine(pickupDirectory, filename); if (!File.Exists(pathAndFilename)) break; diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs index bb300289dfa..4365cee08cb 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs @@ -36,7 +36,7 @@ namespace System.Net.Mime private void SetType(MimeMultiPartType type) { - ContentType.MediaType = "multipart" + "/" + type.ToString().ToLowerInvariant(); + ContentType.MediaType = "multipart/" + type.ToString().ToLowerInvariant(); ContentType.Boundary = GetNextBoundary(); } @@ -249,10 +249,7 @@ namespace System.Net.Mime internal string GetNextBoundary() { int b = Interlocked.Increment(ref s_boundary) - 1; - string boundaryString = "--boundary_" + b.ToString(CultureInfo.InvariantCulture) + "_" + Guid.NewGuid().ToString(null, CultureInfo.InvariantCulture); - - - return boundaryString; + return $"--boundary_{(uint)b}_{Guid.NewGuid()}"; } } } diff --git a/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs b/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs index 74c62684a82..f18ee68a35a 100644 --- a/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs +++ b/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs @@ -39,7 +39,7 @@ namespace System.Net case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_MEMORY: throw new OutOfMemoryException(); default: - Debug.Fail("Unexpected error: " + error.ToString()); + Debug.Fail($"Unexpected error: {error}"); return SocketError.SocketError; } } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Addresses.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Addresses.cs index 59463667713..c898a8539e4 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Addresses.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Addresses.cs @@ -99,8 +99,8 @@ namespace System.Net.NetworkInformation int interfaceIndex = fileContents.IndexOf("interface", firstBrace, blockLength, StringComparison.Ordinal); int afterName = fileContents.IndexOf(';', interfaceIndex); int beforeName = fileContents.LastIndexOf(' ', afterName); - string interfaceName = fileContents.Substring(beforeName + 2, afterName - beforeName - 3); - if (interfaceName != name) + ReadOnlySpan interfaceName = fileContents.AsSpan(beforeName + 2, afterName - beforeName - 3); + if (!interfaceName.SequenceEqual(name)) { continue; } @@ -108,9 +108,8 @@ namespace System.Net.NetworkInformation int indexOfDhcp = fileContents.IndexOf("dhcp-server-identifier", firstBrace, blockLength, StringComparison.Ordinal); int afterAddress = fileContents.IndexOf(';', indexOfDhcp); int beforeAddress = fileContents.LastIndexOf(' ', afterAddress); - string dhcpAddressString = fileContents.Substring(beforeAddress + 1, afterAddress - beforeAddress - 1); - IPAddress? dhcpAddress; - if (IPAddress.TryParse(dhcpAddressString, out dhcpAddress)) + ReadOnlySpan dhcpAddressSpan = fileContents.AsSpan(beforeAddress + 1, afterAddress - beforeAddress - 1); + if (IPAddress.TryParse(dhcpAddressSpan, out IPAddress? dhcpAddress)) { collection.Add(dhcpAddress); } @@ -143,8 +142,8 @@ namespace System.Net.NetworkInformation } } int endOfLine = fileContents.IndexOf(Environment.NewLine, labelIndex, StringComparison.Ordinal); - string addressString = fileContents.Substring(labelIndex + label.Length, endOfLine - (labelIndex + label.Length)); - IPAddress address = IPAddress.Parse(addressString); + ReadOnlySpan addressSpan = fileContents.AsSpan(labelIndex + label.Length, endOfLine - (labelIndex + label.Length)); + IPAddress address = IPAddress.Parse(addressSpan); collection.Add(address); } } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Connections.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Connections.cs index d53d00eb588..ca042d47b74 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Connections.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/StringParsingHelpers.Connections.cs @@ -249,12 +249,11 @@ namespace System.Net.NetworkInformation throw ExceptionHelper.CreateForParseFailure(); } - string remoteAddressString = localAddressAndPort.Substring(0, indexOfColon); - IPAddress localIPAddress = ParseHexIPAddress(remoteAddressString); + IPAddress localIPAddress = ParseHexIPAddress(localAddressAndPort.AsSpan(0, indexOfColon)); - string portString = localAddressAndPort.Substring(indexOfColon + 1, localAddressAndPort.Length - (indexOfColon + 1)); + ReadOnlySpan portSpan = localAddressAndPort.AsSpan(indexOfColon + 1, localAddressAndPort.Length - (indexOfColon + 1)); int localPort; - if (!int.TryParse(portString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out localPort)) + if (!int.TryParse(portSpan, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out localPort)) { throw ExceptionHelper.CreateForParseFailure(); } @@ -270,12 +269,11 @@ namespace System.Net.NetworkInformation throw ExceptionHelper.CreateForParseFailure(); } - string remoteAddressString = colonSeparatedAddress.Substring(0, indexOfColon); - IPAddress ipAddress = ParseHexIPAddress(remoteAddressString); + IPAddress ipAddress = ParseHexIPAddress(colonSeparatedAddress.AsSpan(0, indexOfColon)); - string portString = colonSeparatedAddress.Substring(indexOfColon + 1, colonSeparatedAddress.Length - (indexOfColon + 1)); + ReadOnlySpan portSpan = colonSeparatedAddress.AsSpan(indexOfColon + 1, colonSeparatedAddress.Length - (indexOfColon + 1)); int port; - if (!int.TryParse(portString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out port)) + if (!int.TryParse(portSpan, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out port)) { throw ExceptionHelper.CreateForParseFailure(); } @@ -289,7 +287,7 @@ namespace System.Net.NetworkInformation return Interop.Sys.MapTcpState((int)state); } - internal static IPAddress ParseHexIPAddress(string remoteAddressString) + internal static IPAddress ParseHexIPAddress(ReadOnlySpan remoteAddressString) { if (remoteAddressString.Length <= 8) // IPv4 Address { @@ -307,7 +305,7 @@ namespace System.Net.NetworkInformation // Simply converts the hex string into a long and uses the IPAddress(long) constructor. // Strings passed to this method must be 8 or less characters in length (32-bit address). - private static IPAddress ParseIPv4HexString(string hexAddress) + private static IPAddress ParseIPv4HexString(ReadOnlySpan hexAddress) { IPAddress ipAddress; long addressValue; @@ -328,10 +326,10 @@ namespace System.Net.NetworkInformation // It's represenation in /proc/net/tcp6: 00-00-80-FE 00-00-00-00 FF-5D-15-02 02-04-00-FE // (dashes and spaces added above for readability) // Strings passed to this must be 32 characters in length. - private static IPAddress ParseIPv6HexString(string hexAddress, bool isNetworkOrder = false) + private static IPAddress ParseIPv6HexString(ReadOnlySpan hexAddress, bool isNetworkOrder = false) { Debug.Assert(hexAddress.Length == 32); - byte[] addressBytes = new byte[16]; + Span addressBytes = stackalloc byte[16]; if (isNetworkOrder || !BitConverter.IsLittleEndian) { for (int i = 0; i < 16; i++) diff --git a/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs b/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs index 3893ae10651..8ed63ef9f97 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs @@ -742,7 +742,7 @@ namespace System.Net { sb.Append(SpecialAttributeLiteral + CookieFields.VersionAttributeName + EqualsLiteral); // const strings if (IsQuotedVersion) sb.Append('"'); - sb.Append(m_version.ToString(NumberFormatInfo.InvariantInfo)); + sb.Append(NumberFormatInfo.InvariantInfo, $"{m_version}"); if (IsQuotedVersion) sb.Append('"'); sb.Append(SeparatorLiteral); } diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs index 212e3b6e094..bb7801cbebb 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs @@ -452,7 +452,7 @@ namespace System.Net obj is CredentialHostKey && Equals((CredentialHostKey)obj); public override string ToString() => - Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + AuthenticationType; + string.Create(CultureInfo.InvariantCulture, $"{Host}:{Port}:{AuthenticationType}"); } internal sealed class CredentialKey : IEquatable @@ -543,6 +543,6 @@ namespace System.Net public override bool Equals([NotNullWhen(true)] object? obj) => Equals(obj as CredentialKey); public override string ToString() => - "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + UriPrefix + ":" + AuthenticationType; + string.Create(CultureInfo.InvariantCulture, $"[{UriPrefixLength}]:{UriPrefix}:{AuthenticationType}"); } } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs index 2ebe218c407..10dd32c0316 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SecureChannel.cs @@ -737,7 +737,7 @@ namespace System.Net.Security { if (token.Failed) { - NetEventSource.Error(this, $"Authentication failed. Status: {status.ToString()}, Exception message: {token.GetException()!.Message}"); + NetEventSource.Error(this, $"Authentication failed. Status: {status}, Exception message: {token.GetException()!.Message}"); } } return token; diff --git a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs index fe69152dc10..6a59d81957a 100644 --- a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs +++ b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs @@ -105,9 +105,9 @@ namespace System.Security.Authentication.ExtendedProtection { StringBuilder sb = new StringBuilder(); sb.Append("ProtectionScenario="); - sb.Append(_protectionScenario.ToString()); + sb.Append($"{_protectionScenario}"); sb.Append("; PolicyEnforcement="); - sb.Append(_policyEnforcement.ToString()); + sb.Append($"{_policyEnforcement}"); sb.Append("; CustomChannelBinding="); if (_customChannelBinding == null) diff --git a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs index 0c32b6d906d..27289121acd 100644 --- a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs +++ b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs @@ -501,7 +501,7 @@ namespace System.Net { if (needsHeaderAndBoundary) { - string boundary = "---------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo); + string boundary = $"---------------------{DateTime.Now.Ticks:x}"; headers[HttpKnownHeaderNames.ContentType] = UploadFileContentType + "; boundary=" + boundary; diff --git a/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.cs b/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.cs index 368cf805542..9959c66918e 100644 --- a/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.cs +++ b/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.cs @@ -35,7 +35,7 @@ namespace System.Net } public WebProxy(string Host, int Port) - : this(new Uri("http://" + Host + ":" + Port.ToString(CultureInfo.InvariantCulture)), false, null, null) + : this(new Uri(string.Create(CultureInfo.InvariantCulture, $"http://{Host}:{Port}")), false, null, null) { } @@ -142,9 +142,10 @@ namespace System.Net if (_regexBypassList != null) { + Span stackBuffer = stackalloc char[128]; string matchUriString = input.IsDefaultPort ? - $"{input.Scheme}://{input.Host}" : - $"{input.Scheme}://{input.Host}:{(uint)input.Port}"; + string.Create(null, stackBuffer, $"{input.Scheme}://{input.Host}") : + string.Create(null, stackBuffer, $"{input.Scheme}://{input.Host}:{(uint)input.Port}"); foreach (Regex r in _regexBypassList) { diff --git a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs index 0af0cd5fb14..f19f9a57277 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs +++ b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs @@ -338,8 +338,7 @@ namespace System.Net.WebSockets if (options.ClientMaxWindowBits != WebSocketValidate.MaxDeflateWindowBits) { - builder.Append(ClientWebSocketDeflateConstants.ClientMaxWindowBits).Append('=') - .Append(options.ClientMaxWindowBits.ToString(CultureInfo.InvariantCulture)); + builder.Append(CultureInfo.InvariantCulture, $"{ClientWebSocketDeflateConstants.ClientMaxWindowBits}={options.ClientMaxWindowBits}"); } else { @@ -354,9 +353,7 @@ namespace System.Net.WebSockets if (options.ServerMaxWindowBits != WebSocketValidate.MaxDeflateWindowBits) { - builder.Append("; ") - .Append(ClientWebSocketDeflateConstants.ServerMaxWindowBits).Append('=') - .Append(options.ServerMaxWindowBits.ToString(CultureInfo.InvariantCulture)); + builder.Append(CultureInfo.InvariantCulture, $"; {ClientWebSocketDeflateConstants.ServerMaxWindowBits}={options.ServerMaxWindowBits}"); } if (!options.ServerContextTakeover) diff --git a/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs b/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs index f73025d545b..68eab6c5bba 100644 --- a/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs +++ b/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs @@ -67,7 +67,7 @@ namespace Internal.Win32 } // We really should throw an exception here if errorCode was bad, // but we can't for compatibility reasons. - Debug.Assert(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode); + Debug.Assert(errorCode == 0, $"RegDeleteValue failed. Here's your error code: {errorCode}"); } internal static RegistryKey OpenBaseKey(IntPtr hKey) diff --git a/src/libraries/System.Private.CoreLib/src/System/ApplicationId.cs b/src/libraries/System.Private.CoreLib/src/System/ApplicationId.cs index 30542d17ece..11f807986d3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ApplicationId.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ApplicationId.cs @@ -42,13 +42,9 @@ namespace System sb.Append(Name); if (Culture != null) { - sb.Append(", culture=\""); - sb.Append(Culture); - sb.Append('"'); + sb.Append($", culture=\"{Culture}\""); } - sb.Append(", version=\""); - sb.Append(Version.ToString()); - sb.Append('"'); + sb.Append($", version=\"{Version}\""); if (_publicKeyToken != null) { sb.Append(", publicKeyToken=\""); @@ -57,9 +53,7 @@ namespace System } if (ProcessorArchitecture != null) { - sb.Append(", processorArchitecture =\""); - sb.Append(ProcessorArchitecture); - sb.Append('"'); + sb.Append($", processorArchitecture =\"{ProcessorArchitecture}\""); } return sb.ToString(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/KeyValuePair.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/KeyValuePair.cs index 83f4fda598e..61325d2058f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/KeyValuePair.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/KeyValuePair.cs @@ -11,36 +11,12 @@ namespace System.Collections.Generic public static class KeyValuePair { // Creates a new KeyValuePair from the given values. - public static KeyValuePair Create(TKey key, TValue value) - { - return new KeyValuePair(key, value); - } + public static KeyValuePair Create(TKey key, TValue value) => + new KeyValuePair(key, value); - /// - /// Used by KeyValuePair.ToString to reduce generic code - /// - internal static string PairToString(object? key, object? value) - { - var s = new ValueStringBuilder(stackalloc char[64]); - - s.Append('['); - - if (key != null) - { - s.Append(key.ToString()); - } - - s.Append(", "); - - if (value != null) - { - s.Append(value.ToString()); - } - - s.Append(']'); - - return s.ToString(); - } + /// Used by KeyValuePair.ToString to reduce generic code + internal static string PairToString(object? key, object? value) => + string.Create(null, stackalloc char[256], $"[{key}, {value}]"); } // A KeyValuePair holds a key and a value from a dictionary. diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ActivityTracker.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ActivityTracker.cs index a1f724612d4..8aebbc4f7aa 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ActivityTracker.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/ActivityTracker.cs @@ -321,7 +321,7 @@ namespace System.Diagnostics.Tracing { if (activityInfo == null) return ""; - return Path(activityInfo.m_creator) + "/" + activityInfo.m_uniqueId.ToString(); + return $"{Path(activityInfo.m_creator)}/{activityInfo.m_uniqueId}"; } public override string ToString() diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventCounter.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventCounter.cs index 8a53d569082..0c4460facc3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventCounter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventCounter.cs @@ -71,7 +71,7 @@ namespace System.Diagnostics.Tracing int count = Volatile.Read(ref _count); return count == 0 ? $"EventCounter '{Name}' Count 0" : - $"EventCounter '{Name}' Count {count} Mean {(_sum / count).ToString("n3")}"; + $"EventCounter '{Name}' Count {count} Mean {_sum / count:n3}"; } #region Statistics Calculation diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs index d6093b4fb66..4800a2cde47 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs @@ -3790,7 +3790,9 @@ namespace System.Diagnostics.Tracing try { if (m_outOfBandMessageCount < 16 - 1) // Note this is only if size byte + { m_outOfBandMessageCount++; + } else { if (m_outOfBandMessageCount == 16) @@ -3800,7 +3802,7 @@ namespace System.Diagnostics.Tracing } // send message to debugger - System.Diagnostics.Debugger.Log(0, null, string.Format("EventSource Error: {0}{1}", msg, System.Environment.NewLine)); + Debugger.Log(0, null, $"EventSource Error: {msg}{System.Environment.NewLine}"); // Send it to all listeners. WriteEventString(msg); @@ -5220,14 +5222,12 @@ namespace System.Diagnostics.Tracing sb.AppendLine(""); sb.AppendLine(" "); sb.AppendLine(" "); - sb.Append(""); + sb.AppendLine($" symbol=\"{symbolsName}\">"); } public void AddOpcode(string name, int value) diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs index fee9867d2c9..ed9697d2450 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs @@ -42,7 +42,7 @@ namespace System.Diagnostics.Tracing Publish(); } - public override string ToString() => $"PollingCounter '{Name}' Count 1 Mean {_lastVal.ToString("n3")}"; + public override string ToString() => $"PollingCounter '{Name}' Count 1 Mean {_lastVal:n3}"; private readonly Func _metricProvider; private double _lastVal; diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs index a499d898437..8e8e8c5e689 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs @@ -56,7 +56,7 @@ namespace System fixed (char* lParam = "Environment") { IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST), Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, (IntPtr)lParam, 0, 1000, out IntPtr _); - Debug.Assert(r != IntPtr.Zero, "SetEnvironmentVariable failed: " + Marshal.GetLastPInvokeError()); + Debug.Assert(r != IntPtr.Zero, $"SetEnvironmentVariable failed: {Marshal.GetLastPInvokeError()}"); } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormat.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormat.cs index e9e3618bfc6..593a9ab1e4f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormat.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormat.cs @@ -680,7 +680,7 @@ namespace System } else { - result.Append(year.ToString("D" + tokenLen.ToString(), CultureInfo.InvariantCulture)); + result.Append(year.ToString("D" + tokenLen.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture)); } } bTimeOnly = false; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs index ce6e23b8c85..b4796fd92e6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs @@ -5213,7 +5213,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, if (str[i] <= '\x007f') buffer.Append(str[i]); else - buffer.Append("\\u").Append(((int)str[i]).ToString("x4", CultureInfo.InvariantCulture)); + buffer.Append($"\\u{(int)str[i]:x4}"); } buffer.Append('"'); return buffer.ToString(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewCalendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewCalendar.cs index 4a6aef540a5..2f9d5f729e4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewCalendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/HebrewCalendar.cs @@ -660,7 +660,7 @@ namespace System.Globalization CheckHebrewMonthValue(year, month, era); Debug.Assert(hebrewYearType >= 1 && hebrewYearType <= 6, - "hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year); + $"hebrewYearType should be from 1 to 6, but now hebrewYearType = {hebrewYearType} for hebrew year {year}"); int monthDays = LunarMonthLen[hebrewYearType * MaxMonthPlusOne + month]; if (monthDays == 0) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs index 3834bbeeffe..14da1aa038b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs @@ -389,7 +389,7 @@ namespace System.IO private void ClearReadBufferBeforeWrite() { Debug.Assert(_stream != null); - Debug.Assert(_readPos <= _readLen, "_readPos <= _readLen [" + _readPos + " <= " + _readLen + "]"); + Debug.Assert(_readPos <= _readLen, $"_readPos <= _readLen [{_readPos} <= {_readLen}]"); // No read data in the buffer: if (_readPos == _readLen) @@ -1241,7 +1241,7 @@ namespace System.IO _readPos = _readLen = 0; } - Debug.Assert(newPos == Position, "newPos (=" + newPos + ") == Position (=" + Position + ")"); + Debug.Assert(newPos == Position, $"newPos (={newPos}) == Position (={Position})"); return newPos; } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/BufferedFileStreamStrategy.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/BufferedFileStreamStrategy.cs index 11d21121bee..9aaa16ff519 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/BufferedFileStreamStrategy.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/BufferedFileStreamStrategy.cs @@ -985,7 +985,7 @@ namespace System.IO.Strategies _readPos = _readLen = 0; } - Debug.Assert(newPos == Position, "newPos (=" + newPos + ") == Position (=" + Position + ")"); + Debug.Assert(newPos == Position, $"newPos (={newPos}) == Position (={Position})"); return newPos; } @@ -1023,7 +1023,7 @@ namespace System.IO.Strategies /// private void ClearReadBufferBeforeWrite() { - Debug.Assert(_readPos <= _readLen, "_readPos <= _readLen [" + _readPos + " <= " + _readLen + "]"); + Debug.Assert(_readPos <= _readLen, $"_readPos <= _readLen [{_readPos} <= {_readLen}]"); // No read data in the buffer: if (_readPos == _readLen) diff --git a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs index 9a6eb161d77..f7acdcd21d0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs @@ -1933,14 +1933,14 @@ namespace System /// The number of constant characters outside of interpolation expressions in the interpolated string. /// The number of interpolation expressions in the interpolated string. /// The destination buffer. - /// Upon return, true if the destination may be long enough to support the formatting, or false if it won't be. + /// Upon return, true if the destination may be long enough to support the formatting, or false if it won't be. /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly. - public TryWriteInterpolatedStringHandler(int literalLength, int formattedCount, Span destination, out bool success) + public TryWriteInterpolatedStringHandler(int literalLength, int formattedCount, Span destination, out bool shouldAppend) { _destination = destination; _provider = null; _pos = 0; - _success = success = destination.Length >= literalLength; + _success = shouldAppend = destination.Length >= literalLength; _hasCustomFormatter = false; } @@ -1949,14 +1949,14 @@ namespace System /// The number of interpolation expressions in the interpolated string. /// The destination buffer. /// An object that supplies culture-specific formatting information. - /// Upon return, true if the destination may be long enough to support the formatting, or false if it won't be. + /// Upon return, true if the destination may be long enough to support the formatting, or false if it won't be. /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly. - public TryWriteInterpolatedStringHandler(int literalLength, int formattedCount, Span destination, IFormatProvider? provider, out bool success) + public TryWriteInterpolatedStringHandler(int literalLength, int formattedCount, Span destination, IFormatProvider? provider, out bool shouldAppend) { _destination = destination; _provider = provider; _pos = 0; - _success = success = destination.Length >= literalLength; + _success = shouldAppend = destination.Length >= literalLength; _hasCustomFormatter = provider is not null && DefaultInterpolatedStringHandler.HasCustomFormatter(provider); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Numerics/Plane.cs b/src/libraries/System.Private.CoreLib/src/System/Numerics/Plane.cs index aaab1903dc4..74f9b93fa67 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Numerics/Plane.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Numerics/Plane.cs @@ -321,7 +321,6 @@ namespace System.Numerics /// Returns the string representation of this plane object. /// A string that represents this object. /// The string representation of a object use the formatting conventions of the current culture to format the numeric values in the returned string. For example, a object whose string representation is formatted by using the conventions of the en-US culture might appear as {Normal:<1.1, 2.2, 3.3> D:4.4}. - public override readonly string ToString() => - $"{{Normal:{Normal.ToString()} D:{D.ToString()}}}"; + public override readonly string ToString() => $"{{Normal:{Normal} D:{D}}}"; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs b/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs index 0b483517b97..a0e17bfb349 100644 --- a/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs +++ b/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs @@ -75,9 +75,10 @@ namespace System os = " "; break; } + Span stackBuffer = stackalloc char[128]; _versionString = string.IsNullOrEmpty(_servicePack) ? - os + _version.ToString() : - os + _version.ToString(3) + " " + _servicePack; + string.Create(null, stackBuffer, $"{os}{_version}") : + string.Create(null, stackBuffer, $"{os}{_version.ToString(3)} {_servicePack}"); } return _versionString; diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs index 78ead82418c..16e2b161fc0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs @@ -180,7 +180,7 @@ namespace System.Resources private unsafe int GetNameHash(int index) { - Debug.Assert(index >= 0 && index < _numResources, "Bad index into hash array. index: " + index); + Debug.Assert(index >= 0 && index < _numResources, $"Bad index into hash array. index: {index}"); if (_ums == null) { @@ -196,7 +196,7 @@ namespace System.Resources private unsafe int GetNamePosition(int index) { - Debug.Assert(index >= 0 && index < _numResources, "Bad index into name position array. index: " + index); + Debug.Assert(index >= 0 && index < _numResources, $"Bad index into name position array. index: {index}"); int r; if (_ums == null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/COMException.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/COMException.cs index 5713153e7b0..5fddcf97372 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/COMException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/COMException.cs @@ -48,8 +48,7 @@ namespace System.Runtime.InteropServices { StringBuilder s = new StringBuilder(); - string className = GetType().ToString(); - s.Append(className).Append(" (0x").Append(HResult.ToString("X8", CultureInfo.InvariantCulture)).Append(')'); + s.Append($"{GetType()} (0x{HResult:X8})"); string message = Message; if (!string.IsNullOrEmpty(message)) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ExternalException.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ExternalException.cs index 33c8855e751..13b85e99139 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ExternalException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ExternalException.cs @@ -56,9 +56,8 @@ namespace System.Runtime.InteropServices public override string ToString() { string message = Message; - string className = GetType().ToString(); - string s = className + " (0x" + HResult.ToString("X8", CultureInfo.InvariantCulture) + ")"; + string s = $"{GetType()} (0x{HResult:X8})"; if (!string.IsNullOrEmpty(message)) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/StandardOleMarshalObject.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/StandardOleMarshalObject.Windows.cs index 175c1fc58d0..f5e59ee8c32 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/StandardOleMarshalObject.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/StandardOleMarshalObject.Windows.cs @@ -31,7 +31,7 @@ namespace System.Runtime.InteropServices int hr = Interop.Ole32.CoGetStandardMarshal(ref riid, pUnknown, dwDestContext, IntPtr.Zero, mshlflags, out pStandardMarshal); if (hr == HResults.S_OK) { - Debug.Assert(pStandardMarshal != IntPtr.Zero, "Failed to get marshaler for interface '" + riid.ToString() + "', CoGetStandardMarshal returned S_OK"); + Debug.Assert(pStandardMarshal != IntPtr.Zero, $"Failed to get marshaler for interface '{riid}', CoGetStandardMarshal returned S_OK"); return pStandardMarshal; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/SR.cs b/src/libraries/System.Private.CoreLib/src/System/SR.cs index 097aeffb0d8..6f54dc2000e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/SR.cs +++ b/src/libraries/System.Private.CoreLib/src/System/SR.cs @@ -88,7 +88,7 @@ namespace System string? s = ResourceManager.GetString(key, null); _currentlyLoading.RemoveAt(_currentlyLoading.Count - 1); // Pop - Debug.Assert(s != null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called SR.GetResourceString. Resource name was: \"" + key + "\""); + Debug.Assert(s != null, $"Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called SR.GetResourceString. Resource name was: \"{key}\""); return s ?? key; } catch diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderExceptionFallback.cs b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderExceptionFallback.cs index 94b90901146..e3eb90b5393 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderExceptionFallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderExceptionFallback.cs @@ -51,9 +51,7 @@ namespace System.Text const int MaxLength = 20; for (int i = 0; i < bytesUnknown.Length && i < MaxLength; i++) { - strBytes.Append('['); - strBytes.Append(bytesUnknown[i].ToString("X2", CultureInfo.InvariantCulture)); - strBytes.Append(']'); + strBytes.Append($"[{bytesUnknown[i]:X2}]"); } // In case the string's really long diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderLatin1BestFitFallback.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderLatin1BestFitFallback.cs index 3a83763ea6a..8fb95150018 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderLatin1BestFitFallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderLatin1BestFitFallback.cs @@ -39,7 +39,7 @@ namespace System.Text // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. - Debug.Assert(_iCount < 1, "[EncoderLatin1BestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); + Debug.Assert(_iCount < 1, $"[EncoderLatin1BestFitFallbackBuffer.Fallback(non surrogate)] Fallback char {(int)_cBestFit:X4} caused recursive fallback"); _iCount = _iSize = 1; _cBestFit = TryBestFit(charUnknown); @@ -65,7 +65,7 @@ namespace System.Text // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. - Debug.Assert(_iCount < 1, "[EncoderLatin1BestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); + Debug.Assert(_iCount < 1, $"[EncoderLatin1BestFitFallbackBuffer.Fallback(surrogate)] Fallback char {(int)_cBestFit:X4} caused recursive fallback"); // Go ahead and get our fallback, surrogates don't have best fit _cBestFit = '?'; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Rune.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Rune.cs index 7678b5e4802..3ef7028bacb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Rune.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Rune.cs @@ -140,7 +140,7 @@ namespace System.Text public static explicit operator Rune(int value) => new Rune(value); // Displayed as "'' (U+XXXX)"; e.g., "'e' (U+0065)" - private string DebuggerDisplay => FormattableString.Invariant($"U+{_value:X4} '{(IsValid(_value) ? ToString() : "\uFFFD")}'"); + private string DebuggerDisplay => string.Create(CultureInfo.InvariantCulture, $"U+{_value:X4} '{(IsValid(_value) ? ToString() : "\uFFFD")}'"); /// /// Returns true if and only if this scalar value is ASCII ([ U+0000..U+007F ]) diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeDebug.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeDebug.cs index 4caacbf856c..ecd50f3f7c5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeDebug.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeDebug.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; +using System.Globalization; namespace System.Text { @@ -10,55 +11,39 @@ namespace System.Text [Conditional("DEBUG")] internal static void AssertIsBmpCodePoint(uint codePoint) { - if (!UnicodeUtility.IsBmpCodePoint(codePoint)) - { - Debug.Fail($"The value {ToHexString(codePoint)} is not a valid BMP code point."); - } + Debug.Assert(UnicodeUtility.IsBmpCodePoint(codePoint), $"The value {ToHexString(codePoint)} is not a valid BMP code point."); } [Conditional("DEBUG")] internal static void AssertIsHighSurrogateCodePoint(uint codePoint) { - if (!UnicodeUtility.IsHighSurrogateCodePoint(codePoint)) - { - Debug.Fail($"The value {ToHexString(codePoint)} is not a valid UTF-16 high surrogate code point."); - } + Debug.Assert(UnicodeUtility.IsHighSurrogateCodePoint(codePoint), $"The value {ToHexString(codePoint)} is not a valid UTF-16 high surrogate code point."); } [Conditional("DEBUG")] internal static void AssertIsLowSurrogateCodePoint(uint codePoint) { - if (!UnicodeUtility.IsLowSurrogateCodePoint(codePoint)) - { - Debug.Fail($"The value {ToHexString(codePoint)} is not a valid UTF-16 low surrogate code point."); - } + Debug.Assert(UnicodeUtility.IsLowSurrogateCodePoint(codePoint), $"The value {ToHexString(codePoint)} is not a valid UTF-16 low surrogate code point."); } [Conditional("DEBUG")] internal static void AssertIsValidCodePoint(uint codePoint) { - if (!UnicodeUtility.IsValidCodePoint(codePoint)) - { - Debug.Fail($"The value {ToHexString(codePoint)} is not a valid Unicode code point."); - } + Debug.Assert(UnicodeUtility.IsValidCodePoint(codePoint), $"The value {ToHexString(codePoint)} is not a valid Unicode code point."); } [Conditional("DEBUG")] internal static void AssertIsValidScalar(uint scalarValue) { - if (!UnicodeUtility.IsValidUnicodeScalar(scalarValue)) - { - Debug.Fail($"The value {ToHexString(scalarValue)} is not a valid Unicode scalar value."); - } + Debug.Assert(UnicodeUtility.IsValidUnicodeScalar(scalarValue), $"The value {ToHexString(scalarValue)} is not a valid Unicode scalar value."); } [Conditional("DEBUG")] internal static void AssertIsValidSupplementaryPlaneScalar(uint scalarValue) { - if (!UnicodeUtility.IsValidUnicodeScalar(scalarValue) || UnicodeUtility.IsBmpCodePoint(scalarValue)) - { - Debug.Fail($"The value {ToHexString(scalarValue)} is not a valid supplementary plane Unicode scalar value."); - } + Debug.Assert( + UnicodeUtility.IsValidUnicodeScalar(scalarValue) && !UnicodeUtility.IsBmpCodePoint(scalarValue), + $"The value {ToHexString(scalarValue)} is not a valid supplementary plane Unicode scalar value."); } /// @@ -67,9 +52,6 @@ namespace System.Text /// /// The input value doesn't have to be a real code point in the Unicode codespace. It can be any integer. /// - private static string ToHexString(uint codePoint) - { - return FormattableString.Invariant($"U+{codePoint:X4}"); - } + private static string ToHexString(uint codePoint) => $"U+{codePoint:X4}"; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs index 7e859d19e7a..50faeb94ea2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs @@ -1740,9 +1740,7 @@ namespace System.Text if (decoder != null) { Debug.Assert(!decoder.MustFlush || ((lastChar == (char)0) && (lastByte == -1)), - "[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing" - // + " " + ((int)lastChar).ToString("X4") + " " + lastByte.ToString("X2") - ); + "[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing"); decoder._bytesUsed = (int)(bytes - byteStart); decoder.lastChar = lastChar; diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.FullGlobalizationData.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.FullGlobalizationData.Unix.cs index d1f306abb0f..5a80d7b4486 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.FullGlobalizationData.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.FullGlobalizationData.Unix.cs @@ -125,7 +125,7 @@ namespace System // Get the base offset to prefix in front of the time zone. // Only UTC and its aliases have "(UTC)", handled earlier. All other zones include an offset, even if it's zero. - string baseOffsetText = $"(UTC{(baseUtcOffset >= TimeSpan.Zero ? '+' : '-')}{baseUtcOffset:hh\\:mm})"; + string baseOffsetText = string.Create(null, stackalloc char[128], $"(UTC{(baseUtcOffset >= TimeSpan.Zero ? '+' : '-')}{baseUtcOffset:hh\\:mm})"); // Get the generic location name. string? genericLocationName = null; diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs index 1356e65758c..4756a932715 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs @@ -109,7 +109,7 @@ namespace System // These are expected in environments without time zone globalization data _standardDisplayName = standardAbbrevName; _daylightDisplayName = daylightAbbrevName ?? standardAbbrevName; - _displayName = $"(UTC{(_baseUtcOffset >= TimeSpan.Zero ? '+' : '-')}{_baseUtcOffset:hh\\:mm}) {_id}"; + _displayName = string.Create(null, stackalloc char[256], $"(UTC{(_baseUtcOffset >= TimeSpan.Zero ? '+' : '-')}{_baseUtcOffset:hh\\:mm}) {_id}"); // Try to populate the display names from the globalization data TryPopulateTimeZoneDisplayNamesFromGlobalizationData(_id, _baseUtcOffset, ref _standardDisplayName, ref _daylightDisplayName, ref _displayName); diff --git a/src/libraries/System.Private.CoreLib/src/System/Version.cs b/src/libraries/System.Private.CoreLib/src/System/Version.cs index 455978045f3..bf0ce8e2b4c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Version.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Version.cs @@ -197,55 +197,33 @@ namespace System public bool TryFormat(Span destination, int fieldCount, out int charsWritten) { - string? failureUpperBound = (uint)fieldCount switch + switch (fieldCount) { - > 4 => "4", - >= 3 when _Build == -1 => "2", - 4 when _Revision == -1 => "3", - _ => null - }; - if (failureUpperBound is not null) - { - throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", failureUpperBound), nameof(fieldCount)); - } - - int totalCharsWritten = 0; - - for (int i = 0; i < fieldCount; i++) - { - if (i != 0) - { - if (destination.IsEmpty) - { - charsWritten = 0; - return false; - } - - destination[0] = '.'; - destination = destination.Slice(1); - totalCharsWritten++; - } - - int value = i switch - { - 0 => _Major, - 1 => _Minor, - 2 => _Build, - _ => _Revision - }; - - if (!value.TryFormat(destination, out int valueCharsWritten)) - { + case 0: charsWritten = 0; - return false; - } + return true; - totalCharsWritten += valueCharsWritten; - destination = destination.Slice(valueCharsWritten); + case 1: + return ((uint)_Major).TryFormat(destination, out charsWritten); + + case 2: + return destination.TryWrite($"{(uint)_Major}.{(uint)_Minor}", out charsWritten); + + case 3: + if (_Build == -1) throw CreateBoundException("3"); + return destination.TryWrite($"{(uint)_Major}.{(uint)_Minor}.{(uint)_Build}", out charsWritten); + + case 4: + if (_Build == -1) throw CreateBoundException("2"); + if (_Revision == -1) throw CreateBoundException("3"); + return destination.TryWrite($"{(uint)_Major}.{(uint)_Minor}.{(uint)_Build}.{(uint)_Revision}", out charsWritten); + + default: + throw CreateBoundException("4"); } - charsWritten = totalCharsWritten; - return true; + static Exception CreateBoundException(string failureUpperBound) => + new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", failureUpperBound), nameof(fieldCount)); } bool ISpanFormattable.TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider? provider) => diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs index 9c164eed113..eab7d2e6c28 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs @@ -209,7 +209,7 @@ namespace System.Runtime.Serialization.Json // +"zzzz"; //TimeSpan ts = TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime()); TimeSpan ts = TimeZoneInfo.Local.GetUtcOffset(value.ToLocalTime()); - writer.WriteString(string.Format(CultureInfo.InvariantCulture, "{0:+00;-00}{1:00;00}", ts.Hours, ts.Minutes)); + writer.WriteString(string.Create(CultureInfo.InvariantCulture, $"{ts.Hours:+00;-00}{ts.Minutes:00;00}")); break; case DateTimeKind.Utc: break; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs index 103013f0959..d52d1fabaf4 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs @@ -1420,7 +1420,7 @@ namespace System.Runtime.Serialization.Json _nodeWriter.WriteChars(chars + i, j - i); _nodeWriter.WriteText(BACK_SLASH); _nodeWriter.WriteText('u'); - _nodeWriter.WriteText(string.Format(CultureInfo.InvariantCulture, "{0:x4}", (int)ch)); + _nodeWriter.WriteText($"{(int)ch:x4}"); i = j + 1; } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs index 97e134fe4e3..40584d6d2d5 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs @@ -393,7 +393,7 @@ namespace System.Runtime.Serialization internal static string TryAddLineInfo(XmlReaderDelegator reader, string errorMessage) { if (reader.HasLineInfo()) - return string.Format(CultureInfo.InvariantCulture, "{0} {1}", SR.Format(SR.ErrorInLine, reader.LineNumber, reader.LinePosition), errorMessage); + return string.Create(CultureInfo.InvariantCulture, $"{SR.Format(SR.ErrorInLine, reader.LineNumber, reader.LinePosition)} {errorMessage}"); return errorMessage; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs index 48273f97922..967e30458d3 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs @@ -221,12 +221,12 @@ namespace System.Runtime.Serialization if (isNew) { xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.IdLocalName, - DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "i{0}", objectId)); + DictionaryGlobals.SerializationNamespace, string.Create(CultureInfo.InvariantCulture, $"i{objectId}")); return false; } else { - xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "i{0}", objectId)); + xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Create(CultureInfo.InvariantCulture, $"i{objectId}")); return true; } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs index 50f78a1dd4a..f0be0f4e66f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs @@ -84,7 +84,7 @@ namespace System.Runtime.Serialization string? prefix = writer.LookupPrefix(ns); if (prefix == null) { - prefix = string.Format(CultureInfo.InvariantCulture, "d{0}p{1}", depth, _prefixes); + prefix = string.Create(CultureInfo.InvariantCulture, $"d{depth}p{_prefixes}"); _prefixes++; writer.WriteAttributeString("xmlns", prefix, null, ns); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs index 0fe175fc227..50d93601ae4 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs @@ -1085,7 +1085,7 @@ namespace System.Xml { string value = localNames[i]; if (value == null) - throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); + throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"localNames[{i}]"); if (localName == value) { return i; @@ -1100,7 +1100,7 @@ namespace System.Xml { string value = localNames[i]; if (value == null) - throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); + throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"localNames[{i}]"); if (prefix == value) { return i; @@ -1127,7 +1127,7 @@ namespace System.Xml { XmlDictionaryString value = localNames[i]; if (value == null) - throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); + throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"localNames[{i}]"); if (localName == value) { return i; @@ -1142,7 +1142,7 @@ namespace System.Xml { XmlDictionaryString value = localNames[i]; if (value == null) - throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); + throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"localNames[{i}]"); if (prefix == value) { return i; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs index 13098a6aa29..6692a66ac2b 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs @@ -312,7 +312,7 @@ namespace System.Xml { string value = localNames[i]; if (value == null) - throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); + throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"localNames[{i}]"); if (localName == value) { return i; @@ -338,7 +338,7 @@ namespace System.Xml { XmlDictionaryString value = localNames[i]; if (value == null) - throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i)); + throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"localNames[{i}]"); if (localName == value.Value) { return i; @@ -630,7 +630,7 @@ namespace System.Xml { string value = strings[i]; if (value == null) - throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i)); + throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"strings[{i}]"); if (value == s) { index = i; @@ -650,7 +650,7 @@ namespace System.Xml { XmlDictionaryString value = strings[i]; if (value == null) - throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i)); + throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull($"strings[{i}]"); if (value.Value == s) { index = i; diff --git a/src/libraries/System.Private.Uri/src/System/IPv4AddressHelper.cs b/src/libraries/System.Private.Uri/src/System/IPv4AddressHelper.cs index ef18d5348c9..1f751eeb576 100644 --- a/src/libraries/System.Private.Uri/src/System/IPv4AddressHelper.cs +++ b/src/libraries/System.Private.Uri/src/System/IPv4AddressHelper.cs @@ -41,10 +41,11 @@ namespace System { fixed (char* ipString = name) { + // end includes ports, so changedEnd may be different from end int changedEnd = end; long result = IPv4AddressHelper.ParseNonCanonical(ipString, start, ref changedEnd, true); - // end includes ports, so changedEnd may be different from end - Debug.Assert(result != Invalid, "Failed to parse after already validated: " + name); + + Debug.Assert(result != Invalid, $"Failed to parse after already validated: {name}"); unchecked { diff --git a/src/libraries/System.Private.Uri/src/System/Uri.cs b/src/libraries/System.Private.Uri/src/System/Uri.cs index 4b7e1f4ceff..dc687676f03 100644 --- a/src/libraries/System.Private.Uri/src/System/Uri.cs +++ b/src/libraries/System.Private.Uri/src/System/Uri.cs @@ -4824,27 +4824,22 @@ namespace System // For compatibility with V1.0 parser we restrict the compression scope to Unc Share, i.e. \\host\share\ if (basePart.IsUnc) { - string share = basePart.GetParts(UriComponents.Path | UriComponents.KeepDelimiter, - UriFormat.Unescaped); + ReadOnlySpan share = basePart.GetParts(UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.Unescaped); for (int i = 1; i < share.Length; ++i) { if (share[i] == '/') { - share = share.Substring(0, i); + share = share.Slice(0, i); break; } } + if (basePart.IsImplicitFile) { - return @"\\" - + basePart.GetParts(UriComponents.Host, UriFormat.Unescaped) - + share - + relativePart; + return string.Concat(@"\\", basePart.GetParts(UriComponents.Host, UriFormat.Unescaped), share, relativePart); } - return "file://" - + basePart.GetParts(UriComponents.Host, uriFormat) - + share - + relativePart; + + return string.Concat("file://", basePart.GetParts(UriComponents.Host, uriFormat), share, relativePart); } // It's not obvious but we've checked (for this relativePart format) that baseUti is nor UNC nor DOS path // diff --git a/src/libraries/System.Private.Uri/tests/FunctionalTests/IriRelativeFileResolutionTest.cs b/src/libraries/System.Private.Uri/tests/FunctionalTests/IriRelativeFileResolutionTest.cs index befeda705c5..7715d7669f8 100644 --- a/src/libraries/System.Private.Uri/tests/FunctionalTests/IriRelativeFileResolutionTest.cs +++ b/src/libraries/System.Private.Uri/tests/FunctionalTests/IriRelativeFileResolutionTest.cs @@ -123,8 +123,7 @@ namespace System.PrivateUri.Tests if (!(implicitValue.Equals(explicitValue) || (fileSchemePrefix + implicitValue).Equals(explicitValue))) { errorCount++; - testResults.Append("Property mismatch: " + info.Name + ", implicit value: " + implicitValue - + ", explicit value: " + explicitValue + "; "); + testResults.Append($"Property mismatch: {info.Name}, implicit value: {implicitValue}, explicit value: {explicitValue}; "); } } @@ -133,8 +132,7 @@ namespace System.PrivateUri.Tests if (!implicitString.Equals(explicitString)) { errorCount++; - testResults.Append("ToString mismatch; implicit value: " + implicitString - + ", explicit value: " + explicitString); + testResults.Append($"ToString mismatch; implicit value: {implicitString}, explicit value: {explicitString}"); } errors = testResults.ToString(); @@ -275,8 +273,7 @@ namespace System.PrivateUri.Tests if (!resultValue.Equals(startValue)) { errorCount++; - testResults.Append("Property mismatch: " + info.Name + ", result value: " - + resultValue + ", start value: " + startValue + "; "); + testResults.Append($"Property mismatch: {info.Name}, result value: {resultValue}, start value: {startValue}; "); } } @@ -285,8 +282,7 @@ namespace System.PrivateUri.Tests if (!resultString.Equals(startString)) { errorCount++; - testResults.Append("ToString mismatch; result value: " + resultString - + ", start value: " + startString); + testResults.Append($"ToString mismatch; result value: {resultString}, start value: {startString}"); } errors = testResults.ToString(); diff --git a/src/libraries/System.Private.Uri/tests/FunctionalTests/UriRelativeResolutionTest.cs b/src/libraries/System.Private.Uri/tests/FunctionalTests/UriRelativeResolutionTest.cs index 8a548c85abe..fa4ee9299a8 100644 --- a/src/libraries/System.Private.Uri/tests/FunctionalTests/UriRelativeResolutionTest.cs +++ b/src/libraries/System.Private.Uri/tests/FunctionalTests/UriRelativeResolutionTest.cs @@ -686,12 +686,9 @@ namespace System.PrivateUri.Tests { var result = new StringBuilder(); - byte[] bytes = Encoding.UTF8.GetBytes(input); - - foreach (byte b in bytes) + foreach (byte b in Encoding.UTF8.GetBytes(input)) { - result.Append('%'); - result.Append(b.ToString("X2")); + result.Append($"%{b:X2}"); } return result.ToString(); @@ -710,12 +707,9 @@ namespace System.PrivateUri.Tests continue; } - byte[] bytes = Encoding.UTF8.GetBytes(c.ToString()); - - foreach (byte b in bytes) + foreach (byte b in Encoding.UTF8.GetBytes(c.ToString())) { - result.Append('%'); - result.Append(b.ToString("X2")); + result.Append($"%{b:X2}"); } } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs index 2ee9abc0851..547c8196d58 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs @@ -1388,8 +1388,7 @@ namespace System.Xml.Linq /// The first attribute which is not a namespace attribute or null if the end of attributes has bean reached private XAttribute? GetFirstNonDuplicateNamespaceAttribute(XAttribute candidate) { - Debug.Assert(_omitDuplicateNamespaces, "This method should only be called if we're omitting duplicate namespace attribute." + - "For perf reason it's better to test this flag in the caller method."); + Debug.Assert(_omitDuplicateNamespaces, "This method should only be called if we're omitting duplicate namespace attribute. For perf reason it's better to test this flag in the caller method."); if (!IsDuplicateNamespaceAttribute(candidate)) { return candidate; diff --git a/src/libraries/System.Private.Xml.Linq/tests/XDocument.Common/ManagedNodeWriter.cs b/src/libraries/System.Private.Xml.Linq/tests/XDocument.Common/ManagedNodeWriter.cs index 0e4a7033b10..f8773b85ffc 100644 --- a/src/libraries/System.Private.Xml.Linq/tests/XDocument.Common/ManagedNodeWriter.cs +++ b/src/libraries/System.Private.Xml.Linq/tests/XDocument.Common/ManagedNodeWriter.cs @@ -218,7 +218,7 @@ namespace CoreXml.Test.XLinq /// public void PutCData() { - _nodeQueue.Append(""); + _nodeQueue.Append($""); } /// @@ -226,7 +226,7 @@ namespace CoreXml.Test.XLinq /// public void PutPI() { - _nodeQueue.Append(""); + _nodeQueue.Append($""); } /// @@ -234,7 +234,7 @@ namespace CoreXml.Test.XLinq /// public void PutComment() { - _nodeQueue.Append(""); + _nodeQueue.Append($""); } /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNode.cs index 30e93b62429..a2ab5b21217 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNode.cs @@ -369,8 +369,8 @@ namespace MS.Internal.Xml.Cache /// public void SetLineInfoOffsets(int lineNumOffset, int linePosOffset) { - Debug.Assert(lineNumOffset >= 0 && lineNumOffset <= MaxLineNumberOffset, "Line number offset too large or small: " + lineNumOffset); - Debug.Assert(linePosOffset >= 0 && linePosOffset <= MaxLinePositionOffset, "Line position offset too large or small: " + linePosOffset); + Debug.Assert(lineNumOffset >= 0 && lineNumOffset <= MaxLineNumberOffset, $"Line number offset too large or small: {lineNumOffset}"); + Debug.Assert(linePosOffset >= 0 && linePosOffset <= MaxLinePositionOffset, $"Line position offset too large or small: {linePosOffset}"); _props |= ((uint)lineNumOffset << LineNumberShift); _posOffset = (ushort)linePosOffset; } @@ -380,7 +380,7 @@ namespace MS.Internal.Xml.Cache /// public void SetCollapsedLineInfoOffset(int posOffset) { - Debug.Assert(posOffset >= 0 && posOffset <= MaxCollapsedPositionOffset, "Collapsed text line position offset too large or small: " + posOffset); + Debug.Assert(posOffset >= 0 && posOffset <= MaxCollapsedPositionOffset, $"Collapsed text line position offset too large or small: {posOffset}"); _props |= ((uint)posOffset << CollapsedPositionShift); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/CharEntityEncoderFallback.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/CharEntityEncoderFallback.cs index cfbdc9e8a0d..5cdccd48008 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/CharEntityEncoderFallback.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/CharEntityEncoderFallback.cs @@ -102,7 +102,7 @@ namespace System.Xml if (_parent.CanReplaceAt(index)) { // Create the replacement character entity - _charEntity = string.Format(CultureInfo.InvariantCulture, "&#x{0:X};", new object[] { (int)charUnknown }); + _charEntity = string.Create(null, stackalloc char[64], $"&#x{(int)charUnknown:X};"); _charEntityIndex = 0; return true; } @@ -131,7 +131,7 @@ namespace System.Xml if (_parent.CanReplaceAt(index)) { // Create the replacement character entity - _charEntity = string.Format(CultureInfo.InvariantCulture, "&#x{0:X};", new object[] { SurrogateCharToUtf32(charUnknownHigh, charUnknownLow) }); + _charEntity = string.Create(null, stackalloc char[64], $"&#x{SurrogateCharToUtf32(charUnknownHigh, charUnknownLow):X};"); _charEntityIndex = 0; return true; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs index ffb19d21d52..c39f6155d3d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs @@ -1186,7 +1186,7 @@ namespace System.Xml _currentState = State.Prolog; StringBuilder bufBld = new StringBuilder(128); - bufBld.Append("version=" + _quoteChar + "1.0" + _quoteChar); + bufBld.Append($"version={_quoteChar}1.0{_quoteChar}"); if (_encoding != null) { bufBld.Append(" encoding="); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs index 2e2baa40287..0a4ad3d346e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs @@ -354,7 +354,7 @@ namespace System.Xml.Schema #if DEBUG public override void Dump(StringBuilder bb, SymbolsDictionary symbols, Positions positions) { - bb.Append("\"" + symbols.NameOf(positions[_pos].symbol) + "\""); + bb.Append($"\"{symbols.NameOf(positions[_pos].symbol)}\""); } #endif } @@ -427,7 +427,7 @@ namespace System.Xml.Schema #if DEBUG public override void Dump(StringBuilder bb, SymbolsDictionary symbols, Positions positions) { - bb.Append("[" + namespaceList.ToString() + "]"); + bb.Append($"[{namespaceList}]"); } #endif } @@ -876,7 +876,7 @@ namespace System.Xml.Schema public override void Dump(StringBuilder bb, SymbolsDictionary symbols, Positions positions) { LeftChild.Dump(bb, symbols, positions); - bb.Append("{" + Convert.ToString(min, NumberFormatInfo.InvariantInfo) + ", " + Convert.ToString(max, NumberFormatInfo.InvariantInfo) + "}"); + bb.Append($"{{{Convert.ToString(min, NumberFormatInfo.InvariantInfo)}, {Convert.ToString(max, NumberFormatInfo.InvariantInfo)}}}"); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs index 86fc6cd3953..9f2a8d5c0f7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs @@ -1782,7 +1782,7 @@ namespace System.Xml.Schema //else case 'I': //try to match "INF" INF: - if (s.Substring(i) == "INF") + if (s.AsSpan(i).SequenceEqual("INF")) return TF_float | TF_double | TF_string; else return TF_string; case '.': //try to match ".9999" decimal/float/double diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs index 5312db2a96c..615c405d31b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs @@ -2526,7 +2526,7 @@ namespace System.Xml.Schema } else { - sb.Append("{" + particle.MinOccurs.ToString(NumberFormatInfo.InvariantInfo) + ", " + particle.MaxOccurs.ToString(NumberFormatInfo.InvariantInfo) + "}"); + sb.Append($"{{{particle.MinOccurs.ToString(NumberFormatInfo.InvariantInfo)}, {particle.MaxOccurs.ToString(NumberFormatInfo.InvariantInfo)}}}"); } } #endif diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDateTime.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDateTime.cs index 717bc204e58..71f43082b5e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDateTime.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDateTime.cs @@ -191,7 +191,7 @@ namespace System.Xml.Schema default: { - Debug.Assert(dateTime.Kind == DateTimeKind.Local, "Unknown DateTimeKind: " + dateTime.Kind); + Debug.Assert(dateTime.Kind == DateTimeKind.Local, $"Unknown DateTimeKind: {dateTime.Kind}"); TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(dateTime); if (utcOffset.Ticks < 0) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs index 6ef46a0f686..931735f60c6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs @@ -2464,7 +2464,7 @@ namespace System.Xml.Serialization { if (mappings[j].Name == member.ChoiceIdentifier.MemberName) { - choiceSource = "p[" + j.ToString(CultureInfo.InvariantCulture) + "]"; + choiceSource = $"p[{j}]"; break; } } @@ -2520,17 +2520,17 @@ namespace System.Xml.Serialization for (int i = 0; i < mappings.Length; i++) { MemberMapping mapping = mappings[i]; - string source = "p[" + i.ToString(CultureInfo.InvariantCulture) + "]"; + string source = $"p[{i}]"; string arraySource = source; if (mapping.Xmlns != null) { - arraySource = "((" + mapping.TypeDesc!.CSharpName + ")" + source + ")"; + arraySource = $"(({mapping.TypeDesc!.CSharpName}){source})"; } string? choiceSource = GetChoiceIdentifierSource(mappings, mapping); Member member = new Member(this, source, arraySource, "a", i, mapping, choiceSource); Member anyMember = new Member(this, source, null, "a", i, mapping, choiceSource); if (!mapping.IsSequence) - member.ParamsReadSource = "paramsRead[" + i.ToString(CultureInfo.InvariantCulture) + "]"; + member.ParamsReadSource = $"paramsRead[{i}]"; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) { string nameSpecified = mapping.Name + "Specified"; @@ -2538,7 +2538,7 @@ namespace System.Xml.Serialization { if (mappings[j].Name == nameSpecified) { - member.CheckSpecifiedSource = "p[" + j.ToString(CultureInfo.InvariantCulture) + "]"; + member.CheckSpecifiedSource = $"p[{j}]"; break; } } @@ -2700,15 +2700,15 @@ namespace System.Xml.Serialization for (int i = 0; i < mappings.Length; i++) { MemberMapping mapping = mappings[i]; - string source = "p[" + i.ToString(CultureInfo.InvariantCulture) + "]"; + string source = $"p[{i}]"; string arraySource = source; if (mapping.Xmlns != null) { - arraySource = "((" + mapping.TypeDesc!.CSharpName + ")" + source + ")"; + arraySource = $"(({mapping.TypeDesc!.CSharpName}){source})"; } Member member = new Member(this, source, arraySource, "a", i, mapping); if (!mapping.IsSequence) - member.ParamsReadSource = "paramsRead[" + i.ToString(CultureInfo.InvariantCulture) + "]"; + member.ParamsReadSource = $"paramsRead[{i}]"; members[i] = member; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) @@ -2718,7 +2718,7 @@ namespace System.Xml.Serialization { if (mappings[j].Name == nameSpecified) { - member.CheckSpecifiedSource = "p[" + j.ToString(CultureInfo.InvariantCulture) + "]"; + member.CheckSpecifiedSource = $"p[{j}]"; break; } } @@ -2826,15 +2826,11 @@ namespace System.Xml.Serialization return methodName; } - private string NextMethodName(string name) - { - return "Read" + (++NextMethodNumber).ToString(CultureInfo.InvariantCulture) + "_" + CodeIdentifier.MakeValidInternal(name); - } + private string NextMethodName(string name) => + string.Create(CultureInfo.InvariantCulture, $"Read{++NextMethodNumber}_{CodeIdentifier.MakeValidInternal(name)}"); - private string NextIdName(string name) - { - return "id" + (++_nextIdNumber).ToString(CultureInfo.InvariantCulture) + "_" + CodeIdentifier.MakeValidInternal(name); - } + private string NextIdName(string name) => + string.Create(CultureInfo.InvariantCulture, $"id{(++_nextIdNumber)}_{CodeIdentifier.MakeValidInternal(name)}"); private void WritePrimitive(TypeMapping mapping, string source) { @@ -2961,7 +2957,7 @@ namespace System.Xml.Serialization else { Writer.Write(", "); - Writer.Write(constants[i].Value.ToString(CultureInfo.InvariantCulture) + "L"); + Writer.Write(string.Create(CultureInfo.InvariantCulture, $"{constants[i].Value}L")); } Writer.WriteLine(");"); @@ -3336,7 +3332,7 @@ namespace System.Xml.Serialization string source = RaCodeGen.GetStringForMember("o", mapping.Name, structMapping.TypeDesc); Member member = new Member(this, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); if (!mapping.IsSequence) - member.ParamsReadSource = "paramsRead[" + i.ToString(CultureInfo.InvariantCulture) + "]"; + member.ParamsReadSource = $"paramsRead[{i}]"; member.IsNullable = mapping.TypeDesc!.IsNullable; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) member.CheckSpecifiedSource = RaCodeGen.GetStringForMember("o", mapping.Name + "Specified", structMapping.TypeDesc); @@ -3478,7 +3474,7 @@ namespace System.Xml.Serialization if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) member.CheckSpecifiedSource = RaCodeGen.GetStringForMember("o", mapping.Name + "Specified", structMapping.TypeDesc); if (!mapping.IsSequence) - member.ParamsReadSource = "paramsRead[" + i.ToString(CultureInfo.InvariantCulture) + "]"; + member.ParamsReadSource = $"paramsRead[{i}]"; members[i] = member; } @@ -3581,7 +3577,7 @@ namespace System.Xml.Serialization CreateCollectionInfo? create = (CreateCollectionInfo?)_createMethods[typeDesc]; if (create == null) { - string createName = "create" + (++_nextCreateMethodNumber).ToString(CultureInfo.InvariantCulture) + "_" + typeDesc.Name; + string createName = string.Create(CultureInfo.InvariantCulture, $"create{++_nextCreateMethodNumber}_{typeDesc.Name}"); create = new CreateCollectionInfo(createName, typeDesc); _createMethods.Add(typeDesc, create); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index 010d537da38..41c5c83506d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -373,7 +373,7 @@ namespace System.Xml.Serialization { if (mappings[j].Name == member.ChoiceIdentifier.MemberName) { - choiceSource = "p[" + j.ToString(CultureInfo.InvariantCulture) + "]"; + choiceSource = $"p[{j}]"; break; } } @@ -447,17 +447,17 @@ namespace System.Xml.Serialization for (int i = 0; i < mappings.Length; i++) { MemberMapping mapping = mappings[i]; - string source = "p[" + i.ToString(CultureInfo.InvariantCulture) + "]"; + string source = $"p[{i}]"; string arraySource = source; if (mapping.Xmlns != null) { - arraySource = "((" + mapping.TypeDesc!.CSharpName + ")" + source + ")"; + arraySource = $"(({mapping.TypeDesc!.CSharpName}){source})"; } string choiceSource = GetChoiceIdentifierSource(mappings, mapping); Member member = new Member(this, source, arraySource, "a", i, mapping, choiceSource); Member anyMember = new Member(this, source, null, "a", i, mapping, choiceSource); if (!mapping.IsSequence) - member.ParamsReadSource = "paramsRead[" + i.ToString(CultureInfo.InvariantCulture) + "]"; + member.ParamsReadSource = $"paramsRead[{i}]"; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) { string nameSpecified = mapping.Name + "Specified"; @@ -465,7 +465,7 @@ namespace System.Xml.Serialization { if (mappings[j].Name == nameSpecified) { - member.CheckSpecifiedSource = "p[" + j.ToString(CultureInfo.InvariantCulture) + "]"; + member.CheckSpecifiedSource = $"p[{j}]"; break; } } @@ -685,15 +685,11 @@ namespace System.Xml.Serialization return methodName; } - private string NextMethodName(string name) - { - return "Read" + (++NextMethodNumber).ToString(CultureInfo.InvariantCulture) + "_" + CodeIdentifier.MakeValidInternal(name); - } + private string NextMethodName(string name) => + string.Create(CultureInfo.InvariantCulture, $"Read{++NextMethodNumber}_{CodeIdentifier.MakeValidInternal(name)}"); - private string NextIdName(string name) - { - return "id" + (++_nextIdNumber).ToString(CultureInfo.InvariantCulture) + "_" + CodeIdentifier.MakeValidInternal(name); - } + private string NextIdName(string name) => + string.Create(CultureInfo.InvariantCulture, $"id{++_nextIdNumber}_{CodeIdentifier.MakeValidInternal(name)}"); [RequiresUnreferencedCode("XmlSerializationReader methods have RequiresUnreferencedCode")] private void WritePrimitive(TypeMapping mapping, string source) @@ -1571,7 +1567,7 @@ namespace System.Xml.Serialization string source = RaCodeGen.GetStringForMember("o", mapping.Name, structMapping.TypeDesc); Member member = new Member(this, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); if (!mapping.IsSequence) - member.ParamsReadSource = "paramsRead[" + i.ToString(CultureInfo.InvariantCulture) + "]"; + member.ParamsReadSource = $"paramsRead[{i}]"; member.IsNullable = mapping.TypeDesc!.IsNullable; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) member.CheckSpecifiedSource = RaCodeGen.GetStringForMember("o", mapping.Name + "Specified", structMapping.TypeDesc); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs index 62dc75b1c99..8308e0de386 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs @@ -1241,7 +1241,7 @@ namespace System.Xml.Serialization } else { - _w.WriteAttributeString("arrayType", Soap.Encoding, GetQualifiedName(typeName, typeNs) + "[" + arrayLength.ToString(CultureInfo.InvariantCulture) + "]"); + _w.WriteAttributeString("arrayType", Soap.Encoding, $"{GetQualifiedName(typeName, typeNs)}[{arrayLength}]"); } for (int i = 0; i < arrayLength; i++) { @@ -2605,7 +2605,7 @@ namespace System.Xml.Serialization int xmlnsMember = FindXmlnsIndex(mapping.Members!); if (xmlnsMember >= 0) { - string source = "((" + typeof(System.Xml.Serialization.XmlSerializerNamespaces).FullName + ")p[" + xmlnsMember.ToString(CultureInfo.InvariantCulture) + "])"; + string source = $"(({typeof(System.Xml.Serialization.XmlSerializerNamespaces).FullName})p[{xmlnsMember}])"; Writer.Write("if (pLength > "); Writer.Write(xmlnsMember.ToString(CultureInfo.InvariantCulture)); @@ -2623,7 +2623,7 @@ namespace System.Xml.Serialization if (member.Attribute != null && !member.Ignore) { string index = i.ToString(CultureInfo.InvariantCulture); - string source = "p[" + index + "]"; + string source = $"p[{index}]"; string? specifiedSource = null; int specifiedPosition = 0; @@ -2634,7 +2634,7 @@ namespace System.Xml.Serialization { if (mapping.Members[j].Name == memberNameSpecified) { - specifiedSource = "((bool) p[" + j.ToString(CultureInfo.InvariantCulture) + "])"; + specifiedSource = $"((bool) p[{j}])"; specifiedPosition = j; break; } @@ -2688,7 +2688,7 @@ namespace System.Xml.Serialization { if (mapping.Members[j].Name == memberNameSpecified) { - specifiedSource = "((bool) p[" + j.ToString(CultureInfo.InvariantCulture) + "])"; + specifiedSource = $"((bool) p[{j}])"; specifiedPosition = j; break; } @@ -2720,9 +2720,9 @@ namespace System.Xml.Serialization if (mapping.Members[j].Name == member.ChoiceIdentifier.MemberName) { if (member.ChoiceIdentifier.Mapping!.TypeDesc!.UseReflection) - enumSource = "p[" + j.ToString(CultureInfo.InvariantCulture) + "]"; + enumSource = $"p[{j}]"; else - enumSource = "((" + mapping.Members[j].TypeDesc!.CSharpName + ")p[" + j.ToString(CultureInfo.InvariantCulture) + "]" + ")"; + enumSource = $"(({mapping.Members[j].TypeDesc!.CSharpName })p[{j}])"; break; } } @@ -4427,12 +4427,12 @@ namespace System.Xml.Serialization continue; } int colon = xmlName.LastIndexOf(':'); - string? choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); - string choiceName = colon < 0 ? xmlName : xmlName.Substring(colon + 1); + ReadOnlySpan choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.AsSpan(0, colon); + ReadOnlySpan choiceName = colon < 0 ? xmlName : xmlName.AsSpan(colon + 1); - if (element.Name == choiceName) + if (choiceName.SequenceEqual(element.Name)) { - if ((element.Form == XmlSchemaForm.Unqualified && string.IsNullOrEmpty(choiceNs)) || element.Namespace == choiceNs) + if ((element.Form == XmlSchemaForm.Unqualified && choiceNs.IsEmpty) || choiceNs.SequenceEqual(element.Namespace)) { if (useReflection) enumValue = choiceMapping.Constants[i].Value.ToString(CultureInfo.InvariantCulture); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs index f348fdfa953..1bf9b7069b1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs @@ -407,7 +407,7 @@ namespace System.Xml.Serialization int xmlnsMember = FindXmlnsIndex(mapping.Members!); if (xmlnsMember >= 0) { - string source = "((" + typeof(XmlSerializerNamespaces).FullName + ")p[" + xmlnsMember.ToString(CultureInfo.InvariantCulture) + "])"; + string source = string.Create(CultureInfo.InvariantCulture, $"(({typeof(XmlSerializerNamespaces).FullName})p[{xmlnsMember}])"); ilg.Ldloc(pLengthLoc); ilg.Ldc(xmlnsMember); @@ -422,7 +422,7 @@ namespace System.Xml.Serialization if (member.Attribute != null && !member.Ignore) { - SourceInfo source = new SourceInfo("p[" + i.ToString(CultureInfo.InvariantCulture) + "]", null, null, pLengthLoc.LocalType.GetElementType()!, ilg); + SourceInfo source = new SourceInfo($"p[{i}]", null, null, pLengthLoc.LocalType.GetElementType()!, ilg); SourceInfo? specifiedSource = null; int specifiedPosition = 0; @@ -433,7 +433,7 @@ namespace System.Xml.Serialization { if (mapping.Members[j].Name == memberNameSpecified) { - specifiedSource = new SourceInfo("((bool)p[" + j.ToString(CultureInfo.InvariantCulture) + "])", null, null, typeof(bool), ilg); + specifiedSource = new SourceInfo($"((bool)p[{j}])", null, null, typeof(bool), ilg); specifiedPosition = j; break; } @@ -489,7 +489,7 @@ namespace System.Xml.Serialization { if (mapping.Members[j].Name == memberNameSpecified) { - specifiedSource = new SourceInfo("((bool)p[" + j.ToString(CultureInfo.InvariantCulture) + "])", null, null, typeof(bool), ilg); + specifiedSource = new SourceInfo($"((bool)p[{j}])", null, null, typeof(bool), ilg); specifiedPosition = j; break; } @@ -515,7 +515,7 @@ namespace System.Xml.Serialization ilg.If(); } - string source = "p[" + i.ToString(CultureInfo.InvariantCulture) + "]"; + string source = $"p[{i}]"; string? enumSource = null; if (member.ChoiceIdentifier != null) { @@ -523,7 +523,7 @@ namespace System.Xml.Serialization { if (mapping.Members[j].Name == member.ChoiceIdentifier.MemberName) { - enumSource = "((" + mapping.Members[j].TypeDesc!.CSharpName + ")p[" + j.ToString(CultureInfo.InvariantCulture) + "]" + ")"; + enumSource = $"(({mapping.Members[j].TypeDesc!.CSharpName})p[{j}])"; break; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs index b28f0d6eb8b..c2f54c2715c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs @@ -237,13 +237,13 @@ namespace System.Xml int x = name[0]; int y = name[1]; int u = XmlCharType.CombineSurrogateChar(y, x); - bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture)); + bufBld.Append($"{u:X8}"); position++; copyPosition = 2; } else { - bufBld.Append(((int)name[0]).ToString("X4", CultureInfo.InvariantCulture)); + bufBld.Append($"{(int)name[0]:X4}"); copyPosition = 1; } @@ -282,13 +282,13 @@ namespace System.Xml int x = name[position]; int y = name[position + 1]; int u = XmlCharType.CombineSurrogateChar(y, x); - bufBld.Append(u.ToString("X8", CultureInfo.InvariantCulture)); + bufBld.Append($"{u:X8}"); copyPosition = position + 2; position++; } else { - bufBld.Append(((int)name[position]).ToString("X4", CultureInfo.InvariantCulture)); + bufBld.Append($"{(int)name[position]:X4}"); copyPosition = position + 1; } bufBld.Append('_'); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs index dde7f76f54a..7d8276f0851 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs @@ -234,9 +234,8 @@ namespace System.Xml if (XmlCharType.IsHighSurrogate(invChar) && nextChar != 0) { int combinedChar = XmlCharType.CombineSurrogateChar(nextChar, invChar); - ReadOnlySpan invAndNextChars = stackalloc char[] { invChar, nextChar }; - aStringList[0] = new string(invAndNextChars); - aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", combinedChar); + aStringList[0] = new string(stackalloc char[] { invChar, nextChar }); + aStringList[1] = $"0x{combinedChar:X2}"; } else { @@ -249,7 +248,7 @@ namespace System.Xml { aStringList[0] = invChar.ToString(); } - aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", (int)invChar); + aStringList[1] = $"0x{(int)invChar:X2}"; } return aStringList; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/IteratorDescriptor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/IteratorDescriptor.cs index cc7b1fcc839..9e142049756 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/IteratorDescriptor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/IteratorDescriptor.cs @@ -109,7 +109,7 @@ namespace System.Xml.Xsl.IlGen public static StorageDescriptor Current(LocalBuilder locIter, MethodInfo currentMethod, Type itemStorageType) { Debug.Assert(currentMethod.ReturnType == itemStorageType, - "Type " + itemStorageType + " does not match type of Current property."); + $"Type {itemStorageType} does not match type of Current property."); StorageDescriptor storage = default; storage._location = ItemLocation.Current; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs index dc3bd0d9a38..ab2c645e9a0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs @@ -233,7 +233,7 @@ namespace System.Xml.Xsl.IlGen case 2: arg = _arg2; break; } - Debug.Assert(arg != null, "There is no '" + argNum + "' argument."); + Debug.Assert(arg != null, $"There is no '{argNum}' argument."); return arg; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs index 1c7ea589ad3..29145c1c737 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs @@ -5440,7 +5440,7 @@ namespace System.Xml.Xsl.IlGen { object litLeft, litRight; int cmp; - Debug.Assert(left.XmlType == right.XmlType, "Comparison is not defined between " + left.XmlType + " and " + right.XmlType); + Debug.Assert(left.XmlType == right.XmlType, $"Comparison is not defined between {left.XmlType} and {right.XmlType}"); // Extract objects that represent each literal value litLeft = ExtractLiteralValue(left); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs index 7c5a4c78db4..fb15bb3ecc6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs @@ -1749,7 +1749,7 @@ namespace System.Xml.Xsl.IlGen } else { - Debug.Assert(code != XmlTypeCode.QName, "QName values do not support the " + relOp + " operation"); + Debug.Assert(code != XmlTypeCode.QName, $"QName values do not support the {relOp} operation"); // Push -1, 0, or 1 onto the stack depending upon the result of the comparison _helper.CallCompare(code); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs index b63284285b4..d4f0fe916b9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs @@ -26,7 +26,7 @@ namespace System.Xml.Xsl.Runtime _namespaceUri = namespaceUri; _ebType = ebType; _constrInfo = ebType.GetConstructor(Type.EmptyTypes); - Debug.Assert(_constrInfo != null, "The early bound object type " + ebType.FullName + " must have a public default constructor"); + Debug.Assert(_constrInfo != null, $"The early bound object type {ebType.FullName} must have a public default constructor"); } /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs index 07a97985894..65c54354394 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs @@ -928,7 +928,7 @@ namespace System.Xml.Xsl.Runtime return true; } - Debug.Assert(_state == IteratorState.NoNext, "Illegal state: " + _state); + Debug.Assert(_state == IteratorState.NoNext, $"Illegal state: {_state}"); return false; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs index 83387e02926..f33347623ee 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs @@ -418,7 +418,7 @@ namespace System.Xml.Xsl.Runtime /// public void StartTree(XPathNodeType rootType) { - Debug.Assert(_xstate == XmlState.WithinSequence, "StartTree cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.WithinSequence, $"StartTree cannot be called in the {_xstate} state."); Writer = _seqwrt.StartTree(rootType, _nsmgr, _runtime.NameTable); _rootType = rootType; _xstate = (rootType == XPathNodeType.Attribute || rootType == XPathNodeType.Namespace) ? XmlState.EnumAttrs : XmlState.WithinContent; @@ -429,7 +429,7 @@ namespace System.Xml.Xsl.Runtime /// public void EndTree() { - Debug.Assert(_xstate == XmlState.EnumAttrs || _xstate == XmlState.WithinContent, "EndTree cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.EnumAttrs || _xstate == XmlState.WithinContent, $"EndTree cannot be called in the {_xstate} state."); _seqwrt.EndTree(); _xstate = XmlState.WithinSequence; Writer = null; @@ -445,7 +445,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteStartElementUnchecked(string prefix, string localName, string ns) { - Debug.Assert(_xstate == XmlState.WithinContent, "WriteStartElement cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.WithinContent, $"WriteStartElement cannot be called in the {_xstate} state."); if (_nsmgr != null) _nsmgr.PushScope(); Writer.WriteStartElement(prefix, localName, ns); //reset when enter element @@ -468,7 +468,7 @@ namespace System.Xml.Xsl.Runtime /// public void StartElementContentUnchecked() { - Debug.Assert(_xstate == XmlState.EnumAttrs, "StartElementContent cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.EnumAttrs, $"StartElementContent cannot be called in the {_xstate} state."); // Output any cached namespaces if (_cntNmsp != 0) @@ -483,7 +483,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteEndElementUnchecked(string prefix, string localName, string ns) { - Debug.Assert(_xstate == XmlState.EnumAttrs || _xstate == XmlState.WithinContent, "WriteEndElement cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.EnumAttrs || _xstate == XmlState.WithinContent, $"WriteEndElement cannot be called in the {_xstate} state."); Writer.WriteEndElement(prefix, localName, ns); _xstate = XmlState.WithinContent; _depth--; @@ -503,7 +503,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteStartAttributeUnchecked(string prefix, string localName, string ns) { - Debug.Assert(_xstate == XmlState.EnumAttrs, "WriteStartAttribute cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.EnumAttrs, $"WriteStartAttribute cannot be called in the {_xstate} state."); Writer.WriteStartAttribute(prefix, localName, ns); _xstate = XmlState.WithinAttr; _depth++; @@ -522,7 +522,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteEndAttributeUnchecked() { - Debug.Assert(_xstate == XmlState.WithinAttr, "WriteEndAttribute cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.WithinAttr, $"WriteEndAttribute cannot be called in the {_xstate} state."); Writer.WriteEndAttribute(); _xstate = XmlState.EnumAttrs; _depth--; @@ -538,7 +538,7 @@ namespace System.Xml.Xsl.Runtime public void WriteNamespaceDeclarationUnchecked(string prefix, string ns) { Debug.Assert(prefix != null && ns != null); - Debug.Assert(_xstate == XmlState.EnumAttrs, "WriteNamespaceDeclaration cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.EnumAttrs, $"WriteNamespaceDeclaration cannot be called in the {_xstate} state."); // xmlns:foo="" is illegal Debug.Assert(prefix.Length == 0 || ns.Length != 0); @@ -571,7 +571,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteStringUnchecked(string text) { - Debug.Assert(_xstate != XmlState.WithinSequence && _xstate != XmlState.EnumAttrs, "WriteTextBlock cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate != XmlState.WithinSequence && _xstate != XmlState.EnumAttrs, $"WriteTextBlock cannot be called in the {_xstate} state."); Writer.WriteString(text); } @@ -580,7 +580,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteRawUnchecked(string text) { - Debug.Assert(_xstate != XmlState.WithinSequence && _xstate != XmlState.EnumAttrs, "WriteTextBlockNoEntities cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate != XmlState.WithinSequence && _xstate != XmlState.EnumAttrs, $"WriteTextBlockNoEntities cannot be called in the {_xstate} state."); Writer.WriteRaw(text); } @@ -761,7 +761,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteNamespaceString(string text) { - Debug.Assert(_xstate == XmlState.WithinNmsp, "WriteNamespaceString cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.WithinNmsp, $"WriteNamespaceString cannot be called in the {_xstate} state."); _nodeText.ConcatNoDelimiter(text); } @@ -770,7 +770,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteEndNamespace() { - Debug.Assert(_xstate == XmlState.WithinNmsp, "WriteEndNamespace cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.WithinNmsp, $"WriteEndNamespace cannot be called in the {_xstate} state."); _xstate = XmlState.EnumAttrs; _depth--; @@ -800,7 +800,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteCommentString(string text) { - Debug.Assert(_xstate == XmlState.WithinComment, "WriteCommentString cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.WithinComment, $"WriteCommentString cannot be called in the {_xstate} state."); _nodeText.ConcatNoDelimiter(text); } @@ -809,7 +809,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteEndComment() { - Debug.Assert(_xstate == XmlState.WithinComment, "WriteEndComment cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.WithinComment, $"WriteEndComment cannot be called in the {_xstate} state."); Writer.WriteComment(_nodeText.GetResult()); @@ -843,7 +843,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteProcessingInstructionString(string text) { - Debug.Assert(_xstate == XmlState.WithinPI, "WriteProcessingInstructionString cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.WithinPI, $"WriteProcessingInstructionString cannot be called in the {_xstate} state."); _nodeText.ConcatNoDelimiter(text); } @@ -852,7 +852,7 @@ namespace System.Xml.Xsl.Runtime /// public void WriteEndProcessingInstruction() { - Debug.Assert(_xstate == XmlState.WithinPI, "WriteEndProcessingInstruction cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.WithinPI, $"WriteEndProcessingInstruction cannot be called in the {_xstate} state."); Writer.WriteProcessingInstruction(_piTarget, _nodeText.GetResult()); @@ -1205,7 +1205,7 @@ namespace System.Xml.Xsl.Runtime private void EndCopy(XPathNavigator navigator, bool callChk) { Debug.Assert(navigator.NodeType == XPathNodeType.Element); - Debug.Assert(_xstate == XmlState.WithinContent, "EndCopy cannot be called in the " + _xstate + " state."); + Debug.Assert(_xstate == XmlState.WithinContent, $"EndCopy cannot be called in the {_xstate} state."); if (callChk) WriteEndElement(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs index 4a490b3128f..4bdaf545111 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs @@ -492,7 +492,7 @@ namespace System.Xml.Xsl.Runtime "Values passed to ChangeTypeXsltArgument should be in ILGen's default Clr representation."); Debug.Assert(destinationType == XsltConvert.ObjectType || !destinationType.IsAssignableFrom(value.GetType()), - "No need to call ChangeTypeXsltArgument since value is already assignable to destinationType " + destinationType); + $"No need to call ChangeTypeXsltArgument since value is already assignable to destinationType {destinationType}"); switch (xmlType.TypeCode) { @@ -566,7 +566,7 @@ namespace System.Xml.Xsl.Runtime } } - Debug.Assert(destinationType.IsAssignableFrom(value.GetType()), "ChangeType from type " + value.GetType().Name + " to type " + destinationType.Name + " failed"); + Debug.Assert(destinationType.IsAssignableFrom(value.GetType()), $"ChangeType from type {value.GetType().Name} to type {destinationType.Name} failed"); return value; } @@ -688,7 +688,7 @@ namespace System.Xml.Xsl.Runtime } } - Debug.Assert(XmlILTypeHelper.GetStorageType(xmlType).IsAssignableFrom(value.GetType()), "Xml type " + xmlType + " is not represented in ILGen as " + value.GetType().Name); + Debug.Assert(XmlILTypeHelper.GetStorageType(xmlType).IsAssignableFrom(value.GetType()), $"Xml type {xmlType} is not represented in ILGen as {value.GetType().Name}"); return value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs index a0f45514476..e5b4d1a655b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs @@ -296,7 +296,7 @@ namespace System.Xml.Xsl.Runtime } break; default: - Debug.Assert(CharUtil.IsDecimalDigitOne(startChar), "Unexpected startChar: " + startChar); + Debug.Assert(CharUtil.IsDecimalDigitOne(startChar), $"Unexpected startChar: {startChar}"); zero = (char)(startChar - 1); break; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs index 26b902273ee..a3d392d571c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs @@ -82,7 +82,7 @@ namespace System.Xml.Xsl.Runtime } else { - Debug.Assert(itemType == BooleanType, "Unexpected type of atomic sequence " + itemType.ToString()); + Debug.Assert(itemType == BooleanType, $"Unexpected type of atomic sequence {itemType}"); return item.ValueAsBoolean; } } @@ -126,7 +126,7 @@ namespace System.Xml.Xsl.Runtime } else { - Debug.Assert(itemType == BooleanType, "Unexpected type of atomic sequence " + itemType.ToString()); + Debug.Assert(itemType == BooleanType, $"Unexpected type of atomic sequence {itemType}"); return item.ValueAsBoolean ? 1d : 0d; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs index 2d45c788d2f..c227f2cf9d3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs @@ -340,7 +340,7 @@ namespace System.Xml.Xsl.Runtime } else { - Debug.Assert(itemType == XsltConvert.BooleanType, "Unexpected type of atomic value " + itemType.ToString()); + Debug.Assert(itemType == XsltConvert.BooleanType, $"Unexpected type of atomic value {itemType}"); return item.ValueAsBoolean ? 1d : 0d; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs index 31c779d6abd..c6b516c7fdb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs @@ -353,7 +353,7 @@ namespace System.Xml.Xsl.Runtime } else { - Debug.Assert(itemType == XsltConvert.BooleanType, "Unexpected type of atomic value " + itemType.ToString()); + Debug.Assert(itemType == XsltConvert.BooleanType, $"Unexpected type of atomic value {itemType}"); return TypeCode.Boolean; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs index 879e8d997c7..d27a7d3470e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs @@ -168,7 +168,7 @@ namespace System.Xml.Xsl.XPath [Conditional("DEBUG")] private void ExpectAny(QilNode n) { - Debug.Assert(IsAnyType(n), "Unexpected expression type: " + n.XmlType!.ToString()); + Debug.Assert(IsAnyType(n), $"Unexpected expression type: {n.XmlType}"); } public QilNode ConvertToType(XmlTypeCode requiredType, QilNode n) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs index 0df9d3b3a9d..327bd70c9f6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs @@ -569,7 +569,7 @@ namespace System.Xml.Xsl.Xslt default : nodeType = null ; break; } - Debug.Assert(nodeType != null, "Unexpected nodeKind: " + nodeKind); + Debug.Assert(nodeType != null, $"Unexpected nodeKind: {nodeKind}"); QilNode typeNameCheck = f.IsType(it, nodeType); if (qname != null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs index e8e8b9be0f3..d923e086c9b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs @@ -35,7 +35,7 @@ namespace System.Xml.Xsl.Xslt Debug.Assert(IsDebug, "QName is reserved as the marker for missing values"); break; default: - Debug.Assert(xt.IsNode, "Unexpected expression type: " + xt.ToString()); + Debug.Assert(xt.IsNode, $"Unexpected expression type: {xt}"); break; } } diff --git a/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/XslCompiledTransform.cs b/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/XslCompiledTransform.cs index 54d1fd9a7f8..568072314f3 100644 --- a/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/XslCompiledTransform.cs +++ b/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/XslCompiledTransform.cs @@ -28,14 +28,14 @@ namespace System.Xml.Tests public static MethodInfo GetInstanceMethod(Type type, string methName) { MethodInfo methInfo = type.GetMethod(methName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - Debug.Assert(methInfo != null, "Instance method " + type.Name + "." + methName + " not found"); + Debug.Assert(methInfo != null, $"Instance method {type.Name}.{methName} not found"); return methInfo; } public static MethodInfo GetStaticMethod(Type type, string methName) { MethodInfo methInfo = type.GetMethod(methName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); - Debug.Assert(methInfo != null, "Static method " + type.Name + "." + methName + " not found"); + Debug.Assert(methInfo != null, $"Static method {type.Name}.{methName} not found"); return methInfo; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs index ea0e38e3cde..c2b0151b9ff 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs @@ -113,7 +113,7 @@ namespace System.Reflection.Metadata.Ecma335 { for (int i = 0; i < s_virtualValues!.Length; i++) { - Debug.Assert(s_virtualValues[i] != null, "Missing virtual value for StringHandle.VirtualIndex." + (StringHandle.VirtualIndex)i); + Debug.Assert(s_virtualValues[i] != null, $"Missing virtual value for StringHandle.VirtualIndex.{(StringHandle.VirtualIndex)i}"); } } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/tests/src/TestUtils/TestUtils.cs b/src/libraries/System.Reflection.MetadataLoadContext/tests/src/TestUtils/TestUtils.cs index ac71eddcbaa..5b6635cabfa 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/tests/src/TestUtils/TestUtils.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/tests/src/TestUtils/TestUtils.cs @@ -123,7 +123,7 @@ namespace System.Reflection.Tests for (int i = 0; i < bytes.Length; i++) { - builder.Append(bytes[i].ToString("X2")); + builder.Append($"{bytes[i]:X2}"); } return builder.ToString(); diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheUsage.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheUsage.cs index 4b6df845ef5..73ed9f30d3d 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheUsage.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheUsage.cs @@ -717,7 +717,7 @@ namespace System.Runtime.Caching if (_cEntriesInUse == 0) return 0; - Debug.Assert(maxFlush > 0, "maxFlush is not greater than 0, instead is " + maxFlush); + Debug.Assert(maxFlush > 0, $"maxFlush is not greater than 0, instead is {maxFlush}"); Debug.Assert(_cEntriesInFlush == 0, "_cEntriesInFlush == 0"); UsageEntryRef inFlushHead = UsageEntryRef.INVALID; diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs index c80daaac7a8..9d3cb73564b 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs @@ -38,7 +38,7 @@ namespace System.Runtime.Caching DateTimeOffset lastWrite; long fileSize; s_fcn.StartMonitoring(path, new OnChangedCallback(OnChanged), out _fcnState, out lastWrite, out fileSize); - uniqueId = path + lastWrite.UtcDateTime.Ticks.ToString("X", CultureInfo.InvariantCulture) + fileSize.ToString("X", CultureInfo.InvariantCulture); + uniqueId = $"{path}{lastWrite.UtcDateTime.Ticks:X}{fileSize:X}"; _lastModified = lastWrite; } else diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntryChangeMonitor.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntryChangeMonitor.cs index b04afc5149e..05d3aeca4b1 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntryChangeMonitor.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntryChangeMonitor.cs @@ -39,7 +39,7 @@ namespace System.Runtime.Caching MemoryCacheEntry entry = cache.GetEntry(k); DateTime utcCreated = s_DATETIME_MINVALUE_UTC; StartMonitoring(cache, entry, ref hasChanged, ref utcCreated); - uniqueId = k + utcCreated.Ticks.ToString("X", CultureInfo.InvariantCulture); + uniqueId = $"{k}{utcCreated.Ticks:X}"; _lastModified = utcCreated; } else @@ -56,7 +56,7 @@ namespace System.Runtime.Caching DateTime utcCreated = s_DATETIME_MINVALUE_UTC; StartMonitoring(cache, entry, ref hasChanged, ref utcCreated); sb.Append(key); - sb.Append(utcCreated.Ticks.ToString("X", CultureInfo.InvariantCulture)); + sb.Append($"{utcCreated.Ticks:X}"); if (utcCreated > _lastModified) { _lastModified = utcCreated; diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/PhysicalMemoryMonitor.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/PhysicalMemoryMonitor.cs index 9d4ba7c85cd..901754ba815 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/PhysicalMemoryMonitor.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/PhysicalMemoryMonitor.cs @@ -91,11 +91,7 @@ namespace System.Runtime.Caching } #if PERF - Debug.WriteLine(string.Format("PhysicalMemoryMonitor.GetPercentToTrim: percent={0:N}, lastTrimPercent={1:N}, secondsSinceTrim={2:N}{3}", - percent, - lastTrimPercent, - ticksSinceTrim/TimeSpan.TicksPerSecond, - Environment.NewLine)); + Debug.WriteLine($"PhysicalMemoryMonitor.GetPercentToTrim: percent={percent:N}, lastTrimPercent={lastTrimPercent:N}, secondsSinceTrim={ticksSinceTrim/TimeSpan.TicksPerSecond:N}{Environment.NewLine}"); #endif } @@ -111,8 +107,7 @@ namespace System.Runtime.Caching } _pressureHigh = Math.Max(3, physicalMemoryLimitPercentage); _pressureLow = Math.Max(1, _pressureHigh - 9); - Dbg.Trace("MemoryCacheStats", "PhysicalMemoryMonitor.SetLimit: _pressureHigh=" + _pressureHigh + - ", _pressureLow=" + _pressureLow); + Dbg.Trace($"MemoryCacheStats", "PhysicalMemoryMonitor.SetLimit: _pressureHigh={_pressureHigh}, _pressureLow={_pressureLow}"); } } } diff --git a/src/libraries/System.Runtime.Extensions/tests/System/Convert.FromHexString.cs b/src/libraries/System.Runtime.Extensions/tests/System/Convert.FromHexString.cs index 488cda85c35..da7a83aab1c 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/Convert.FromHexString.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/Convert.FromHexString.cs @@ -25,7 +25,7 @@ namespace System.Tests for (int i = 0; i < values.Length; i++) { values[i] = (byte)i; - sb.Append(i.ToString("X2")); + sb.Append($"{i:X2}"); } TestSequence(values, sb.ToString()); diff --git a/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToHexString.cs b/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToHexString.cs index 3b0986a46e4..b92685667dd 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToHexString.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/Convert.ToHexString.cs @@ -24,7 +24,7 @@ namespace System.Tests for (int i = 0; i < values.Length; i++) { values[i] = (byte)i; - sb.Append(i.ToString("X2")); + sb.Append($"{i:X2}"); } Assert.Equal(sb.ToString(), Convert.ToHexString(values)); diff --git a/src/libraries/System.Runtime.Extensions/tests/System/Math.cs b/src/libraries/System.Runtime.Extensions/tests/System/Math.cs index fbe995267af..44f4bf6d282 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/Math.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/Math.cs @@ -1949,7 +1949,7 @@ namespace System.Tests public static void BigMul128_Unsigned(ulong a, ulong b, string result) { ulong high = Math.BigMul(a, b, out ulong low); - Assert.Equal(result, high.ToString("X16") + low.ToString("X16")); + Assert.Equal(result, $"{high:X16}{low:X16}"); } [Theory] @@ -1968,7 +1968,7 @@ namespace System.Tests public static void BigMul128_Signed(long a, long b, string result) { long high = Math.BigMul(a, b, out long low); - Assert.Equal(result, high.ToString("X16") + low.ToString("X16")); + Assert.Equal(result, $"{high:X16}{low:X16}"); } [Theory] diff --git a/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System.Runtime.InteropServices.RuntimeInformation.csproj b/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System.Runtime.InteropServices.RuntimeInformation.csproj index 2ee0caf2d56..1e04c274aa8 100644 --- a/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System.Runtime.InteropServices.RuntimeInformation.csproj +++ b/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System.Runtime.InteropServices.RuntimeInformation.csproj @@ -40,6 +40,7 @@ + diff --git a/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.Windows.cs b/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.Windows.cs index 0177eec2317..2cd38459dc7 100644 --- a/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.Windows.cs +++ b/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.Windows.cs @@ -21,10 +21,11 @@ namespace System.Runtime.InteropServices OperatingSystem os = Environment.OSVersion; Version v = os.Version; + Span stackBuffer = stackalloc char[256]; const string Version = "Microsoft Windows"; s_osDescription = osDescription = string.IsNullOrEmpty(os.ServicePack) ? - $"{Version} {(uint)v.Major}.{(uint)v.Minor}.{(uint)v.Build}" : - $"{Version} {(uint)v.Major}.{(uint)v.Minor}.{(uint)v.Build} {os.ServicePack}"; + string.Create(null, stackBuffer, $"{Version} {(uint)v.Major}.{(uint)v.Minor}.{(uint)v.Build}") : + string.Create(null, stackBuffer, $"{Version} {(uint)v.Major}.{(uint)v.Minor}.{(uint)v.Build} {os.ServicePack}"); } return osDescription; diff --git a/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.cs b/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.cs index df0fb53273d..6e892ce5204 100644 --- a/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.cs +++ b/src/libraries/System.Runtime.InteropServices.RuntimeInformation/src/System/Runtime/InteropServices/RuntimeInformation/RuntimeInformation.cs @@ -17,19 +17,16 @@ namespace System.Runtime.InteropServices { if (s_frameworkDescription == null) { - string? versionString = typeof(object).Assembly.GetCustomAttribute()?.InformationalVersion; + ReadOnlySpan versionString = typeof(object).Assembly.GetCustomAttribute()?.InformationalVersion; // Strip the git hash if there is one - if (versionString != null) + int plusIndex = versionString.IndexOf('+'); + if (plusIndex != -1) { - int plusIndex = versionString.IndexOf('+'); - if (plusIndex != -1) - { - versionString = versionString.Substring(0, plusIndex); - } + versionString = versionString.Slice(0, plusIndex); } - s_frameworkDescription = !string.IsNullOrWhiteSpace(versionString) ? $"{FrameworkName} {versionString}" : FrameworkName; + s_frameworkDescription = !versionString.Trim().IsEmpty ? $"{FrameworkName} {versionString}" : FrameworkName; } return s_frameworkDescription; diff --git a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetObjectForNativeVariantTests.cs b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetObjectForNativeVariantTests.cs index a4fe32e9c02..d8a6bc398f5 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetObjectForNativeVariantTests.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/GetObjectForNativeVariantTests.cs @@ -61,7 +61,7 @@ namespace System.Runtime.InteropServices.Tests [FieldOffset(0)] public TypeUnion m_Variant; [FieldOffset(0)] public decimal m_decimal; - public override string ToString() => "0x" + m_Variant.vt.ToString("X"); + public override string ToString() => $"0x{m_Variant.vt:X}"; } // Taken from wtypes.h diff --git a/src/libraries/System.Runtime.Numerics/tests/BigInteger/BigIntegerToStringTests.cs b/src/libraries/System.Runtime.Numerics/tests/BigInteger/BigIntegerToStringTests.cs index 060200698b2..2bbc23476c5 100644 --- a/src/libraries/System.Runtime.Numerics/tests/BigInteger/BigIntegerToStringTests.cs +++ b/src/libraries/System.Runtime.Numerics/tests/BigInteger/BigIntegerToStringTests.cs @@ -1676,11 +1676,11 @@ namespace System.Numerics.Tests { if (upper) { - output = output + chars[start].ToString("X"); + output = $"{output}{chars[start]:X}"; } else { - output = output + chars[start].ToString("x"); + output = $"{output}{chars[start]:x}"; } } diff --git a/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTypes.RuntimeOnly.cs b/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTypes.RuntimeOnly.cs index de485ec10b5..a7cc9748bab 100644 --- a/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTypes.RuntimeOnly.cs +++ b/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTypes.RuntimeOnly.cs @@ -2387,7 +2387,7 @@ public class Family sb.AppendLine("Family members:"); foreach (var member in this.Members) { - sb.AppendLine(" " + member); + sb.AppendLine($" {member}"); } return sb.ToString(); @@ -2404,7 +2404,7 @@ public class FamilyForStress sb.AppendLine("Family members:"); foreach (var member in this.Members) { - sb.AppendLine(" " + member); + sb.AppendLine($" {member}"); } return sb.ToString(); diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OidLookup.Unix.cs b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OidLookup.Unix.cs index 63862ea65b4..cfef4e4d096 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OidLookup.Unix.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/Internal/Cryptography/OidLookup.Unix.cs @@ -30,7 +30,7 @@ namespace Internal.Cryptography case -1: /* OpenSSL internal error */ throw Interop.Crypto.CreateOpenSslCryptographicException(); default: - Debug.Assert(result == 0, "LookupFriendlyNameByOid returned unexpected result " + result); + Debug.Assert(result == 0, $"LookupFriendlyNameByOid returned unexpected result {result}"); // The lookup may have left errors in this case, clean up for precaution. Interop.Crypto.ErrClearError(); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlAttribute.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlAttribute.cs index ed06c365672..761fc37439a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlAttribute.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlAttribute.cs @@ -25,7 +25,7 @@ namespace System.Security.Cryptography.Xml public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { - strBuilder.Append(" " + Name + "=\""); + strBuilder.Append($" {Name}=\""); strBuilder.Append(Utils.EscapeAttributeValue(Value)); strBuilder.Append('"'); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs index fb1f9c599cf..7d3174b0780 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlElement.cs @@ -91,7 +91,7 @@ namespace System.Security.Cryptography.Xml if (IsInNodeSet) { - strBuilder.Append(""); + strBuilder.Append($""); } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlProcessingInstruction.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlProcessingInstruction.cs index 2bc2502eb9f..de71302a1c0 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlProcessingInstruction.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXmlProcessingInstruction.cs @@ -33,7 +33,7 @@ namespace System.Security.Cryptography.Xml strBuilder.Append(" 0)) - strBuilder.Append(" " + Value); + strBuilder.Append(' ').Append(Value); strBuilder.Append("?>"); if (docPos == DocPosition.BeforeRootElement) strBuilder.Append((char)10); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs index 5f7a5090097..e70615426c2 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs @@ -249,7 +249,7 @@ namespace System.Security.Cryptography.Xml { Debug.Assert(o != null, "o != null"); - return $"{o.GetType().Name}#{o.GetHashCode().ToString("x8", CultureInfo.InvariantCulture)}"; + return $"{o.GetType().Name}#{o.GetHashCode():x8}"; } /// diff --git a/src/libraries/System.Security.Cryptography.Xml/tests/XmlDsigXsltTransformTest.cs b/src/libraries/System.Security.Cryptography.Xml/tests/XmlDsigXsltTransformTest.cs index 906e9676165..1fa91a3c912 100644 --- a/src/libraries/System.Security.Cryptography.Xml/tests/XmlDsigXsltTransformTest.cs +++ b/src/libraries/System.Security.Cryptography.Xml/tests/XmlDsigXsltTransformTest.cs @@ -111,7 +111,7 @@ namespace System.Security.Cryptography.Xml.Tests int b = s.ReadByte(); while (b != -1) { - sb.Append(b.ToString("X2")); + sb.Append($"{b:X2}"); b = s.ReadByte(); } return sb.ToString(); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs index 7b20e996ad6..eacc8ca6861 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs @@ -14,7 +14,7 @@ namespace System.ServiceModel.Syndication IXmlLineInfo lineInfo = reader as IXmlLineInfo; if (lineInfo != null && lineInfo.HasLineInfo()) { - error = string.Format(CultureInfo.InvariantCulture, "{0} {1}", SR.Format(SR.ErrorInLine, lineInfo.LineNumber, lineInfo.LinePosition), SR.Format(error)); + error = $"{SR.Format(SR.ErrorInLine, lineInfo.LineNumber, lineInfo.LinePosition)} {error}"; } return error; } diff --git a/src/libraries/System.ServiceModel.Syndication/tests/Utils/XmlDiffDocument.cs b/src/libraries/System.ServiceModel.Syndication/tests/Utils/XmlDiffDocument.cs index f06e87cda95..be087593f9b 100644 --- a/src/libraries/System.ServiceModel.Syndication/tests/Utils/XmlDiffDocument.cs +++ b/src/libraries/System.ServiceModel.Syndication/tests/Utils/XmlDiffDocument.cs @@ -1612,7 +1612,7 @@ namespace System.ServiceModel.Syndication.Tests w.WriteString(Value); break; default: - Debug.Assert(false, "Wrong type for text-like node : " + _nodetype.ToString()); + Debug.Assert(false, $"Wrong type for text-like node : {_nodetype}"); break; } } diff --git a/src/libraries/System.Speech/src/Result/RecognizedPhrase.cs b/src/libraries/System.Speech/src/Result/RecognizedPhrase.cs index 446d744cae0..ebcde98e50a 100644 --- a/src/libraries/System.Speech/src/Result/RecognizedPhrase.cs +++ b/src/libraries/System.Speech/src/Result/RecognizedPhrase.cs @@ -1166,7 +1166,7 @@ namespace System.Speech.Recognition private string DisplayDebugInfo() { - return string.Format("'rule={0}", _rule); + return $"'rule={_rule}"; } internal Grammar _grammar; internal string _rule; diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.cs index 01208d21183..ab66bca82c3 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/BaseCodePageEncoding.cs @@ -337,7 +337,7 @@ namespace System.Text if (pCodePageIndex->CodePage == codePage) { Debug.Assert(pCodePageIndex->ByteCount == 1 || pCodePageIndex->ByteCount == 2, - "[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePageIndex->ByteCount + ") in table"); + $"[BaseCodePageEncoding] Code page ({codePage}) has invalid byte size ({pCodePageIndex->ByteCount}) in table"); // Return what it says for byte count return pCodePageIndex->ByteCount; } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs index 531f2687624..5255ed67b97 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DBCSCodePageEncoding.cs @@ -399,7 +399,7 @@ namespace System.Text if (bOutOfOrder) { Debug.Assert((arrayTemp.Length / 2) < 20, - "[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page " + CodePage + ", not " + arrayTemp.Length / 2); + $"[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page {CodePage}, not {arrayTemp.Length / 2}"); for (int i = 0; i < arrayTemp.Length - 2; i += 2) { diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs index 0d9bed68345..e232be86168 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderBestFitFallback.cs @@ -84,7 +84,7 @@ namespace System.Text // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. - Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); + Debug.Assert(_iCount < 1, $"[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char {(int)_cBestFit:X4} caused recursive fallback"); _iCount = _iSize = 1; _cBestFit = TryBestFit(charUnknown); @@ -106,7 +106,7 @@ namespace System.Text // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. - Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); + Debug.Assert(_iCount < 1, $"[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char {(int)_cBestFit:X4} caused recursive fallback"); // Go ahead and get our fallback, surrogates don't have best fit _cBestFit = '?'; diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs index 2f4042f334c..7a27288fd4e 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs @@ -188,7 +188,7 @@ namespace System.Text // We should've read in GBLast4ByteCode 4 byte sequences Debug.Assert(count4Byte == GBLast4ByteCode + 1, - "[GB18030Encoding.LoadManagedCodePage] Expected 0x99FB to be last 4 byte offset, found 0x" + count4Byte.ToString("X4", CultureInfo.InvariantCulture)); + $"[GB18030Encoding.LoadManagedCodePage] Expected 0x99FB to be last 4 byte offset, found 0x{count4Byte:X4}"); } // Is4Byte @@ -242,7 +242,7 @@ namespace System.Text if (charLeftOver != 0) { Debug.Assert(char.IsHighSurrogate(charLeftOver), - "[GB18030Encoding.GetBytes] leftover character should be high surrogate, not 0x" + ((int)charLeftOver).ToString("X4", CultureInfo.InvariantCulture)); + $"[GB18030Encoding.GetBytes] leftover character should be high surrogate, not 0x{(int)charLeftOver:X4}"); // If our next char isn't a low surrogate, then we need to do fallback. if (!char.IsLowSurrogate(ch)) @@ -272,7 +272,7 @@ namespace System.Text byte byte2 = (byte)((offset % 0x0a) + 0x30); offset /= 0x0a; Debug.Assert(offset < 0x6f, - "[GB18030Encoding.GetBytes](1) Expected offset < 0x6f, not 0x" + offset.ToString("X2", CultureInfo.InvariantCulture)); + $"[GB18030Encoding.GetBytes](1) Expected offset < 0x6f, not 0x{offset:X2}"); charLeftOver = (char)0; if (!buffer.AddByte((byte)(offset + 0x90), byte2, byte3, byte4)) @@ -322,7 +322,7 @@ namespace System.Text byte byte2 = (byte)((iBytes % 0x0a) + 0x30); iBytes /= 0x0a; Debug.Assert(iBytes < 0x7e, - "[GB18030Encoding.GetBytes]Expected iBytes < 0x7e, not 0x" + iBytes.ToString("X2", CultureInfo.InvariantCulture)); + $"[GB18030Encoding.GetBytes]Expected iBytes < 0x7e, not 0x{iBytes:X2}"); if (!buffer.AddByte((byte)(iBytes + 0x81), byte2, byte3, byte4)) break; } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs index e630706877a..204c45dbd39 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISCIIEncoding.cs @@ -58,7 +58,7 @@ namespace System.Text // Legal windows code pages are between Devanagari and Punjabi Debug.Assert(_defaultCodePage >= CodeDevanagari && _defaultCodePage <= CodePunjabi, - "[ISCIIEncoding] Code page (" + codePage + " isn't supported by ISCIIEncoding!"); + $"[ISCIIEncoding] Code page ({codePage} isn't supported by ISCIIEncoding!"); // This shouldn't really be possible if (_defaultCodePage < CodeDevanagari || _defaultCodePage > CodePunjabi) @@ -237,7 +237,7 @@ namespace System.Text // We only know how to map from Unicode to pages from Devanagari to Punjabi (2 to 11) Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi, - "[ISCIIEncoding.GetBytes]Code page (" + currentCodePage + " shouldn't appear in ISCII from Unicode table!"); + $"[ISCIIEncoding.GetBytes]Code page ({currentCodePage} shouldn't appear in ISCII from Unicode table!"); } // Safe to add our byte now @@ -252,7 +252,7 @@ namespace System.Text { // This one needs another byte Debug.Assert((indicTwoBytes >> 12) > 0 && (indicTwoBytes >> 12) <= 3, - "[ISCIIEncoding.GetBytes]Expected indicTwoBytes from 1-3, not " + (indicTwoBytes >> 12)); + $"[ISCIIEncoding.GetBytes]Expected indicTwoBytes from 1-3, not {(indicTwoBytes >> 12)}"); // Already did buffer checking, but... if (!buffer.AddByte(s_SecondIndicByte[indicTwoBytes >> 12])) @@ -350,7 +350,7 @@ namespace System.Text // Get our current code page index (some code pages are dups) int currentCodePageIndex = -1; Debug.Assert(currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi, - "[ISCIIEncoding.GetChars]Decoder code page must be >= Devanagari and <= Punjabi, not " + currentCodePage); + $"[ISCIIEncoding.GetChars]Decoder code page must be >= Devanagari and <= Punjabi, not {currentCodePage}"); if (currentCodePage >= CodeDevanagari && currentCodePage <= CodePunjabi) { diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs index dbfa9a5cdbd..e76e3ea160a 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs @@ -403,9 +403,9 @@ namespace System.Text.RegularExpressions { var sb = new StringBuilder(); - sb.AppendLine("Direction: " + (RightToLeft ? "right-to-left" : "left-to-right")); - sb.AppendLine("Anchor: " + RegexPrefixAnalyzer.AnchorDescription(LeadingAnchor)); - sb.AppendLine(""); + sb.AppendLine($"Direction: {(RightToLeft ? "right-to-left" : "left-to-right")}"); + sb.AppendLine($"Anchor: {RegexPrefixAnalyzer.AnchorDescription(LeadingAnchor)}"); + sb.AppendLine(); if (BoyerMoorePrefix != null) { diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexLWCGCompiler.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexLWCGCompiler.cs index 52bd5b89ec2..4c8fe4f9190 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexLWCGCompiler.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexLWCGCompiler.cs @@ -47,7 +47,7 @@ namespace System.Text.RegularExpressions _hasTimeout = hasTimeout; // Pick a unique number for the methods we generate. - object regexNum = (uint)Interlocked.Increment(ref s_regexCount); // object to box once instead of twice below + uint regexNum = (uint)Interlocked.Increment(ref s_regexCount); // Get a description of the regex to use in the name. This is helpful when profiling, and is opt-in. string description = string.Empty; diff --git a/src/libraries/System.Text.RegularExpressions/tests/RegexCharacterSetTests.cs b/src/libraries/System.Text.RegularExpressions/tests/RegexCharacterSetTests.cs index b11071d595e..a029d679c8b 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/RegexCharacterSetTests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/RegexCharacterSetTests.cs @@ -82,7 +82,7 @@ namespace System.Text.RegularExpressions.Tests [InlineData('\u0100')] public void SingleExpected(char c) { - string s = @"\u" + ((int)c).ToString("X4"); + string s = $@"\u{(int)c:X4}"; var set = new HashSet() { c }; // One diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionsEtwProvider.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionsEtwProvider.cs index 0be2514b344..5da12d24196 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionsEtwProvider.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionsEtwProvider.cs @@ -1168,16 +1168,14 @@ namespace System.Transactions { // GUID with dash if (str.Length >= 36) { - string str_part1 = str.Substring(0, 36); - Guid.TryParse(str_part1, out guid); + Guid.TryParse(str.AsSpan(0, 36), out guid); } } else { if (str.Length >= 32) { - string str_part1 = str.Substring(0, 32); - Guid.TryParse(str_part1, out guid); + Guid.TryParse(str.AsSpan(0, 32), out guid); } } SetCurrentThreadActivityId(guid); diff --git a/src/libraries/System.ValueTuple/tests/ExtensionsTests.cs b/src/libraries/System.ValueTuple/tests/ExtensionsTests.cs index a4db2b40b5e..758f7d8da62 100644 --- a/src/libraries/System.ValueTuple/tests/ExtensionsTests.cs +++ b/src/libraries/System.ValueTuple/tests/ExtensionsTests.cs @@ -674,26 +674,26 @@ namespace System.Tests { var builder = new StringBuilder(); if (x1 > 0) { builder.Append(x1); } - if (x2 > 0) { builder.Append(" " + x2); } - if (x3 > 0) { builder.Append(" " + x3); } - if (x4 > 0) { builder.Append(" " + x4); } - if (x5 > 0) { builder.Append(" " + x5); } - if (x6 > 0) { builder.Append(" " + x6); } - if (x7 > 0) { builder.Append(" " + x7); } - if (x8 > 0) { builder.Append(" " + x8); } - if (x9 > 0) { builder.Append(" " + x9); } - if (x10 > 0) { builder.Append(" " + x10); } - if (x11 > 0) { builder.Append(" " + x11); } - if (x12 > 0) { builder.Append(" " + x12); } - if (x13 > 0) { builder.Append(" " + x13); } - if (x14 > 0) { builder.Append(" " + x14); } - if (x15 > 0) { builder.Append(" " + x15); } - if (x16 > 0) { builder.Append(" " + x16); } - if (x17 > 0) { builder.Append(" " + x17); } - if (x18 > 0) { builder.Append(" " + x18); } - if (x19 > 0) { builder.Append(" " + x19); } - if (x20 > 0) { builder.Append(" " + x20); } - if (x21 > 0) { builder.Append(" " + x21); } + if (x2 > 0) { builder.Append($" {x2}"); } + if (x3 > 0) { builder.Append($" {x3}"); } + if (x4 > 0) { builder.Append($" {x4}"); } + if (x5 > 0) { builder.Append($" {x5}"); } + if (x6 > 0) { builder.Append($" {x6}"); } + if (x7 > 0) { builder.Append($" {x7}"); } + if (x8 > 0) { builder.Append($" {x8}"); } + if (x9 > 0) { builder.Append($" {x9}"); } + if (x10 > 0) { builder.Append($" {x10}"); } + if (x11 > 0) { builder.Append($" {x11}"); } + if (x12 > 0) { builder.Append($" {x12}"); } + if (x13 > 0) { builder.Append($" {x13}"); } + if (x14 > 0) { builder.Append($" {x14}"); } + if (x15 > 0) { builder.Append($" {x15}"); } + if (x16 > 0) { builder.Append($" {x16}"); } + if (x17 > 0) { builder.Append($" {x17}"); } + if (x18 > 0) { builder.Append($" {x18}"); } + if (x19 > 0) { builder.Append($" {x19}"); } + if (x20 > 0) { builder.Append($" {x20}"); } + if (x21 > 0) { builder.Append($" {x21}"); } return builder.ToString(); } diff --git a/src/libraries/System.Web.HttpUtility/src/System/Web/HttpUtility.cs b/src/libraries/System.Web.HttpUtility/src/System/Web/HttpUtility.cs index b6b46d1fda9..d991cc61d3f 100644 --- a/src/libraries/System.Web.HttpUtility/src/System/Web/HttpUtility.cs +++ b/src/libraries/System.Web.HttpUtility/src/System/Web/HttpUtility.cs @@ -66,11 +66,11 @@ namespace System.Web { if (string.IsNullOrEmpty(keys[i])) { - sb.AppendFormat("{0}&", UrlEncode(value)); + sb.Append(UrlEncode(value)).Append('&'); } else { - sb.AppendFormat("{0}={1}&", keys[i], UrlEncode(value)); + sb.AppendFormat($"{keys[i]}={UrlEncode(value)}&"); } } } diff --git a/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs b/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs index 868418b2292..658665d3c66 100644 --- a/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs +++ b/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs @@ -14,8 +14,7 @@ namespace System.Web.Util { private static void AppendCharAsUnicodeJavaScript(StringBuilder builder, char c) { - builder.Append("\\u"); - builder.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)); + builder.Append($"\\u{(int)c:x4}"); } private static bool CharRequiresJavaScriptEncoding(char c) => diff --git a/src/tasks/AppleAppBuilder/Xcode.cs b/src/tasks/AppleAppBuilder/Xcode.cs index 9c0af486b64..b79387da224 100644 --- a/src/tasks/AppleAppBuilder/Xcode.cs +++ b/src/tasks/AppleAppBuilder/Xcode.cs @@ -222,7 +222,7 @@ internal class Xcode if (!string.IsNullOrEmpty(DiagnosticPorts)) { - defines.AppendLine("\nadd_definitions(-DDIAGNOSTIC_PORTS=\"" + DiagnosticPorts + "\")"); + defines.AppendLine($"\nadd_definitions(-DDIAGNOSTIC_PORTS=\"{DiagnosticPorts}\")"); } cmakeLists = cmakeLists.Replace("%Defines%", defines.ToString()); @@ -272,7 +272,7 @@ internal class Xcode .Append("-S.") .Append(" -B").Append(projectName) .Append(" -GXcode") - .Append(" -DCMAKE_SYSTEM_NAME=" + targetName) + .Append(" -DCMAKE_SYSTEM_NAME=").Append(targetName) .Append(deployTarget); File.WriteAllText(Path.Combine(binDir, "runtime.h"), @@ -334,30 +334,30 @@ internal class Xcode case TargetNames.iOS: sdk = "iphoneos"; args.Append(" -arch arm64") - .Append(" -sdk " + sdk); + .Append(" -sdk ").Append(sdk); break; case TargetNames.iOSsim: sdk = "iphonesimulator"; args.Append(" -arch arm64") - .Append(" -sdk " + sdk); + .Append(" -sdk ").Append(sdk); break; case TargetNames.tvOS: sdk = "appletvos"; args.Append(" -arch arm64") - .Append(" -sdk " + sdk); + .Append(" -sdk ").Append(sdk); break; case TargetNames.tvOSsim: sdk = "appletvsimulator"; args.Append(" -arch arm64") - .Append(" -sdk " + sdk); + .Append(" -sdk ").Append(sdk); break; default: sdk = "maccatalyst"; - args.Append(" -scheme \"" + Path.GetFileNameWithoutExtension(xcodePrjPath) + "\"") + args.Append(" -scheme \"").Append(Path.GetFileNameWithoutExtension(xcodePrjPath)).Append('"') .Append(" -destination \"generic/platform=macOS,name=Any Mac,variant=Mac Catalyst\"") .Append(" -UseModernBuildSystem=YES") - .Append(" -archivePath \"" + Path.GetDirectoryName(xcodePrjPath) + "\"") - .Append(" -derivedDataPath \"" + Path.GetDirectoryName(xcodePrjPath) + "\"") + .Append(" -archivePath \"").Append(Path.GetDirectoryName(xcodePrjPath)).Append('"') + .Append(" -derivedDataPath \"").Append(Path.GetDirectoryName(xcodePrjPath)).Append('"') .Append(" IPHONEOS_DEPLOYMENT_TARGET=14.2"); break; } @@ -369,20 +369,20 @@ internal class Xcode case TargetNames.iOSsim: sdk = "iphonesimulator"; args.Append(" -arch x86_64") - .Append(" -sdk " + sdk); + .Append(" -sdk ").Append(sdk); break; case TargetNames.tvOSsim: sdk = "appletvsimulator"; args.Append(" -arch x86_64") - .Append(" -sdk " + sdk); + .Append(" -sdk ").Append(sdk); break; default: sdk = "maccatalyst"; - args.Append(" -scheme \"" + Path.GetFileNameWithoutExtension(xcodePrjPath) + "\"") + args.Append(" -scheme \"").Append(Path.GetFileNameWithoutExtension(xcodePrjPath)).Append('"') .Append(" -destination \"generic/platform=macOS,name=Any Mac,variant=Mac Catalyst\"") .Append(" -UseModernBuildSystem=YES") - .Append(" -archivePath \"" + Path.GetDirectoryName(xcodePrjPath) + "\"") - .Append(" -derivedDataPath \"" + Path.GetDirectoryName(xcodePrjPath) + "\"") + .Append(" -archivePath \"").Append(Path.GetDirectoryName(xcodePrjPath)).Append('"') + .Append(" -derivedDataPath \"").Append(Path.GetDirectoryName(xcodePrjPath)).Append('"') .Append(" IPHONEOS_DEPLOYMENT_TARGET=13.5"); break; } diff --git a/src/tasks/WasmAppBuilder/PInvokeTableGenerator.cs b/src/tasks/WasmAppBuilder/PInvokeTableGenerator.cs index 603fbcf1700..bdd84c295ee 100644 --- a/src/tasks/WasmAppBuilder/PInvokeTableGenerator.cs +++ b/src/tasks/WasmAppBuilder/PInvokeTableGenerator.cs @@ -209,7 +209,7 @@ public class PInvokeTableGenerator : Task // The signature of the interp entry function // This is a gsharedvt_in signature sb.Append("typedef void "); - sb.Append(" (*WasmInterpEntrySig_" + cb_index + ") ("); + sb.Append($" (*WasmInterpEntrySig_{cb_index}) ("); int pindex = 0; if (method.ReturnType.Name != "Void") { sb.Append("int"); @@ -247,13 +247,13 @@ public class PInvokeTableGenerator : Task if (pindex > 0) sb.Append(','); sb.Append(MapType(method.GetParameters()[pindex].ParameterType)); - sb.Append(" arg" + pindex); + sb.Append($" arg{pindex}"); pindex++; } sb.Append(") { \n"); if (!is_void) sb.Append(MapType(method.ReturnType) + " res;\n"); - sb.Append("((WasmInterpEntrySig_" + cb_index + ")wasm_native_to_interp_ftndescs [" + cb_index + "].func) ("); + sb.Append($"((WasmInterpEntrySig_{cb_index})wasm_native_to_interp_ftndescs [{cb_index}].func) ("); pindex = 0; if (!is_void) { sb.Append("&res"); @@ -263,7 +263,7 @@ public class PInvokeTableGenerator : Task foreach (var p in method.GetParameters()) { if (pindex > 0) sb.Append(", "); - sb.Append("&arg" + aindex); + sb.Append($"&arg{aindex}"); pindex++; aindex++; }