Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use more string interpolation #55738

Merged
merged 3 commits into from
Jul 16, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ public void WriteProperty(string name, object value)
}
else
{
Builder.AppendFormat( "null");
Builder.Append( "null");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,11 @@ public override string ToString()
: NativeErrorCode.ToString(CultureInfo.InvariantCulture);
if (HResult == E_FAIL)
{
s.AppendFormat($" ({nativeErrorString})");
s.Append($" ({nativeErrorString})");
}
else
{
s.AppendFormat($" ({HResult:X8}, {nativeErrorString})");
s.Append($" ({HResult:X8}, {nativeErrorString})");
}

if (!(string.IsNullOrEmpty(message)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Globalization;
using System.Text;
using System.Xml;

Expand Down Expand Up @@ -92,7 +93,7 @@ public string DataViewSettingCollectionString
foreach (DataTable dt in _dataSet.Tables)
{
DataViewSetting ds = _dataViewSettingsCollection[dt];
builder.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "<{0} Sort=\"{1}\" RowFilter=\"{2}\" RowStateFilter=\"{3}\"/>", dt.EncodedTableName, ds.Sort, ds.RowFilter, ds.RowStateFilter);
builder.Append(CultureInfo.InvariantCulture, $"<{dt.EncodedTableName} Sort=\"{ds.Sort}\" RowFilter=\"{ds.RowFilter}\" RowStateFilter=\"{ds.RowStateFilter}\"/>");
}
builder.Append("</DataViewSettingCollectionString>");
return builder.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1157,12 +1157,11 @@ private static string GetAssociationDetails()
sb.AppendLine("------------------------------");

string open = GetAssociationString(0, 1 /* ASSOCSTR_COMMAND */, ".txt", "open");
sb.AppendFormat("Open command: {0}", open);
sb.AppendLine();
sb.AppendLine($"Open command: {open}");

string progId = GetAssociationString(0, 20 /* ASSOCSTR_PROGID */, ".txt", null);
sb.AppendFormat("ProgID: {0}", progId);
sb.AppendLine();
sb.AppendLine("ProgID: {progId}");
stephentoub marked this conversation as resolved.
Show resolved Hide resolved

return sb.ToString();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1174,10 +1174,10 @@ string PrintProcesses(Process currentProcess)
StringBuilder builder = new StringBuilder();
foreach (Process process in Process.GetProcesses())
{
builder.AppendFormat("Pid: '{0}' Name: '{1}'", process.Id, process.ProcessName);
builder.Append($"Pid: '{process.Id}' Name: '{process.ProcessName}'");
try
{
builder.AppendFormat(" Main module: '{0}'", process.MainModule.FileName);
builder.Append($" Main module: '{process.MainModule.FileName}'");
}
catch
{
Expand All @@ -1186,7 +1186,7 @@ string PrintProcesses(Process currentProcess)
builder.AppendLine();
}

builder.AppendFormat("Current process id: {0} Process name: '{1}'", currentProcess.Id, currentProcess.ProcessName);
builder.Append($"Current process id: {currentProcess.Id} Process name: '{currentProcess.ProcessName}'");
return builder.ToString();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,21 +222,21 @@ private static string PrintCodePointsForDebug(IEnumerable<char> input)
if (!char.IsHighSurrogate(thisChar) || !enumerator.MoveNext())
{
// not a high surrogate, or a high surrogate at the end of the sequence - it goes as-is
sb.AppendFormat(CultureInfo.InvariantCulture, "{0:X4} ", (uint)thisChar);
sb.Append($"{(uint)thisChar:X4} ");
}
else
{
char secondChar = enumerator.Current;
if (!char.IsLowSurrogate(secondChar))
{
// previous char was a standalone high surrogate char - send it as-is
sb.AppendFormat(CultureInfo.InvariantCulture, "{0:X4} ", (uint)thisChar);
sb.Append($"{(uint)thisChar:X4} ");
goto SawStandaloneChar;
}
else
{
// surrogate pair - extract supplementary code point
sb.AppendFormat(CultureInfo.InvariantCulture, "{0:X4} ", (uint)char.ConvertToUtf32(thisChar, secondChar));
sb.Append($"{(uint)char.ConvertToUtf32(thisChar, secondChar):X4} ");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ public virtual string MultipleLabels(int[] offsets)
int length = offsets.Length;
for (int i = 0; i < length; i++)
{
if (i == 0) sb.AppendFormat("(");
else sb.AppendFormat(", ");
if (i == 0) sb.Append("(");
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
else sb.Append(", ");
sb.Append(Label(offsets[i]));
}
sb.AppendFormat(")");
sb.Append(")");
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
return sb.ToString();
}

Expand All @@ -57,7 +57,7 @@ public virtual string EscapedString(string str)
else if (ch == '\r') sb.Append("\\r");
else if (ch == '\"') sb.Append("\\\"");
else if (ch == '\\') sb.Append("\\");
else if (ch < 0x20 || ch >= 0x7f) sb.AppendFormat("\\u{0:x4}", (int)ch);
else if (ch < 0x20 || ch >= 0x7f) sb.Append($"\\u{(int)ch:x4}");
else sb.Append(ch);
}
return "\"" + sb.ToString() + "\"";
Expand All @@ -69,11 +69,11 @@ public virtual string SigByteArrayToString(byte[] sig)
int length = sig.Length;
for (int i = 0; i < length; i++)
{
if (i == 0) sb.AppendFormat("SIG [");
else sb.AppendFormat(" ");
if (i == 0) sb.Append("SIG [");
else sb.Append(' ');
sb.Append(Int8ToHex(sig[i]));
}
sb.AppendFormat("]");
sb.Append(']');
return sb.ToString();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ internal void ToString(TraceFormat traceFormat, StringBuilder sb)
else
sb.AppendLine();

sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At);
sb.Append(" ").Append(word_At).Append(' ');

bool isAsync = false;
Type? declaringType = mb.DeclaringType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -811,16 +811,16 @@ private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset,
if (tokenLen <= 1)
{
// 'z' format e.g "-7"
result.AppendFormat(CultureInfo.InvariantCulture, "{0:0}", offset.Hours);
result.Append(CultureInfo.InvariantCulture, $"{offset.Hours:0}");
}
else
{
// 'zz' or longer format e.g "-07"
result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}", offset.Hours);
result.Append(CultureInfo.InvariantCulture, $"{offset.Hours:00}");
if (tokenLen >= 3)
{
// 'zzz*' or longer format e.g "-07:30"
result.AppendFormat(CultureInfo.InvariantCulture, ":{0:00}", offset.Minutes);
result.Append(CultureInfo.InvariantCulture, $":{offset.Minutes:00}");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@

namespace System.Globalization
{
/// <summary>
/// This class implements a set of methods for retrieving
/// </summary>
/// <summary>Represents the result of mapping a string to its sort key.</summary>
public sealed partial class SortKey
{
private readonly CompareInfo _compareInfo;
Expand Down Expand Up @@ -67,20 +65,11 @@ public static int Compare(SortKey sortkey1, SortKey sortkey2)
return new ReadOnlySpan<byte>(key1Data).SequenceCompareTo(key2Data);
}

public override bool Equals([NotNullWhen(true)] object? value)
{
return value is SortKey other
&& new ReadOnlySpan<byte>(_keyData).SequenceEqual(other._keyData);
}
public override bool Equals([NotNullWhen(true)] object? value) =>
value is SortKey other && new ReadOnlySpan<byte>(_keyData).SequenceEqual(other._keyData);

public override int GetHashCode()
{
return _compareInfo.GetHashCode(_string, _options);
}
public override int GetHashCode() => _compareInfo.GetHashCode(_string, _options);

public override string ToString()
{
return "SortKey - " + _compareInfo.Name + ", " + _options + ", " + _string;
}
public override string ToString() => $"SortKey - {_compareInfo.Name}, {_options}, {_string}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,8 @@ public class LocalVariableInfo
public virtual int LocalIndex => 0;
public virtual bool IsPinned => false;
protected LocalVariableInfo() { }
public override string ToString()
{
string toString = LocalType.ToString() + " (" + LocalIndex + ")";

if (IsPinned)
toString += " (pinned)";

return toString;
}
public override string ToString() => IsPinned ?
$"{LocalType} ({LocalIndex}) (pinned)" :
$"{LocalType} ({LocalIndex})";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ public FileBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediato
{
// We really don't think this should happen - we always
// expect the neutral locale's resources to be present.
throw new MissingManifestResourceException(SR.MissingManifestResource_NoNeutralDisk + Environment.NewLineConst + "baseName: " + _mediator.BaseNameField + " locationInfo: " + (_mediator.LocationInfo == null ? "<null>" : _mediator.LocationInfo.FullName) + " fileName: " + _mediator.GetResourceFileName(culture));
string? locationInfo = _mediator.LocationInfo == null ? "<null>" : _mediator.LocationInfo.FullName;
throw new MissingManifestResourceException($"{SR.MissingManifestResource_NoNeutralDisk}{Environment.NewLineConst}baseName: {_mediator.BaseNameField} locationInfo: {locationInfo} fileName: {_mediator.GetResourceFileName(culture)}");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ public event Action<AssemblyLoadContext>? Unloading

public string? Name => _name;

public override string ToString() => "\"" + Name + "\" " + GetType().ToString() + " #" + _id;
public override string ToString() => $"\"{Name}\" {GetType()} #{_id}";

public static IEnumerable<AssemblyLoadContext> All
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,22 +52,9 @@ public string FullName
{
if (_fullName == null)
{
if (string.IsNullOrEmpty(Profile))
{
_fullName =
Identifier +
ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix +
Version.ToString();
}
else
{
_fullName =
Identifier +
ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix +
Version.ToString() +
ComponentSeparator + ProfileKey + KeyValueSeparator +
Profile;
}
_fullName = string.IsNullOrEmpty(Profile) ?
$"{Identifier}{ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix}{Version}" :
$"{Identifier}{ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix}{Version}{ComponentSeparator + ProfileKey + KeyValueSeparator}{Profile}";
}

Debug.Assert(_fullName != null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ internal static void ThrowLastBytesRecursive(byte[] bytesUnknown)
{
if (strBytes.Length > 0)
strBytes.Append(' ');
strBytes.AppendFormat(CultureInfo.InvariantCulture, "\\x{0:X2}", bytesUnknown[i]);
strBytes.Append($"\\x{bytesUnknown[i]:X2}");
}
// In case the string's really long
if (i == 20)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1769,7 +1769,7 @@ private string GeneratePrefix(string ns, XmlDictionaryString? xNs)
while (true)
{
int prefixId = _elements![_depth].PrefixId++;
prefix = string.Concat("d", _depth.ToString(CultureInfo.InvariantCulture), "p", prefixId.ToString(CultureInfo.InvariantCulture));
prefix = string.Create(CultureInfo.InvariantCulture, $"d{_depth}p{prefixId}");

if (_nsMgr.LookupNamespace(prefix) == null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public virtual void WriteXmlnsAttribute(string? prefix, string namespaceUri)
if (LookupPrefix(namespaceUri) != null)
return;
#pragma warning suppress 56506 // Microsoft, namespaceUri is already checked
stephentoub marked this conversation as resolved.
Show resolved Hide resolved
prefix = namespaceUri.Length == 0 ? string.Empty : string.Concat("d", namespaceUri.Length.ToString(System.Globalization.NumberFormatInfo.InvariantInfo));
prefix = namespaceUri.Length == 0 ? string.Empty : $"d{namespaceUri.Length}";
}
WriteAttributeString("xmlns", prefix, null, namespaceUri);
}
Expand Down
6 changes: 2 additions & 4 deletions src/libraries/System.Private.Uri/src/System/Uri.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4864,12 +4864,10 @@ private static string CombineUri(Uri basePart, string relativePart, UriFormat ur
return basePart.Scheme + ':' + relativePart;
}

// Got absolute relative path, and the base is nor FILE nor a DOS path (checked at the method start)
// Got absolute relative path, and the base is not FILE nor a DOS path (checked at the method start)
if (basePart.HostType == Flags.IPv6HostType)
{
left = basePart.GetParts(UriComponents.Scheme | UriComponents.UserInfo, uriFormat)
+ '[' + basePart.DnsSafeHost + ']'
+ basePart.GetParts(UriComponents.KeepDelimiter | UriComponents.Port, uriFormat);
left = $"{basePart.GetParts(UriComponents.Scheme | UriComponents.UserInfo, uriFormat)}[{basePart.DnsSafeHost}]{basePart.GetParts(UriComponents.KeepDelimiter | UriComponents.Port, uriFormat)}";
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ public void TestTextReadBinHex_24()
bytes = DataReader.ReadContentAsBinHex(bbb, 0, bbb.Length);
for (int i = 0; i < bytes; i++)
{
output.AppendFormat(bbb[i].ToString());
output.Append(bbb[i]);
}
}

Expand Down Expand Up @@ -866,7 +866,7 @@ public void TestTextReadBinHex_24()
bytes = DataReader.ReadElementContentAsBinHex(bbb, 0, bbb.Length);
for (int i = 0; i < bytes; i++)
{
output.AppendFormat(bbb[i].ToString());
output.Append(bbb[i]);
}
}
if (TestLog.Compare(output.ToString().Length, 1735, "Expected Length : 1735"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ public override string ToString()

for (int i = 0; i < _hashTable.Length; i++)
{
bldr.AppendFormat("{0,4}: ", i);
bldr.Append($"{i,4}: ");

infoAtom = _hashTable[i];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2109,7 +2109,7 @@ private static string GetStateName(State state)

private string GeneratePrefix()
{
string genPrefix = "p" + (_nsTop - 2).ToString("d", CultureInfo.InvariantCulture);
string genPrefix = string.Create(CultureInfo.InvariantCulture, $"p{_nsTop - 2:d}");
if (LookupNamespace(genPrefix) == null)
{
return genPrefix;
Expand All @@ -2119,7 +2119,7 @@ private string GeneratePrefix()
string s;
do
{
s = string.Concat(genPrefix, i.ToString(CultureInfo.InvariantCulture));
s = string.Create(CultureInfo.InvariantCulture, $"{genPrefix}{i}");
i++;
} while (LookupNamespace(s) != null);
return s;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1569,7 +1569,7 @@ private void Dump(StringBuilder bb, BitSet[] followpos, int[][] transitionTable)
}
else
{
bb.AppendFormat(" {0:000} ", transitionTable[i][j]);
bb.Append($" {transitionTable[i][j]:000} ");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -884,7 +884,7 @@ public IList<XPathNavigator> DocOrderDistinct(IList<XPathNavigator> seq)
/// </summary>
public string GenerateId(XPathNavigator navigator)
{
return string.Concat("ID", _docOrderCmp.GetDocumentIndex(navigator).ToString(CultureInfo.InvariantCulture), navigator.UniqueId);
return string.Create(CultureInfo.InvariantCulture, $"ID{_docOrderCmp.GetDocumentIndex(navigator)}{navigator.UniqueId}");
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1076,7 +1076,7 @@ public int TestReadBase64ReadsTheContent()
for (int i = 0; i < bytes; i++)
{
CError.Write(bbb[i].ToString());
output.AppendFormat(bbb[i].ToString());
output.Append(bbb[i]);
}
}
CError.WriteLine();
Expand Down
Loading