Skip to content

Commit

Permalink
Clean up string formatting in a variety of places (#50267)
Browse files Browse the repository at this point in the history
Mostly just replacing string.Format calls with equivalent interpolated string uses.  In some cases, I replaced lots of string creations with a StringBuilder or equivalent.
  • Loading branch information
stephentoub authored Apr 5, 2021
1 parent c5eeedb commit 0c79392
Show file tree
Hide file tree
Showing 78 changed files with 219 additions and 460 deletions.
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;

namespace System.Reflection
{
Expand Down Expand Up @@ -439,15 +440,33 @@ private void Init(object pca)
#region Object Override
public override string ToString()
{
string ctorArgs = "";
for (int i = 0; i < ConstructorArguments.Count; i++)
ctorArgs += string.Format(i == 0 ? "{0}" : ", {0}", ConstructorArguments[i]);
var vsb = new ValueStringBuilder(stackalloc char[256]);

vsb.Append('[');
vsb.Append(Constructor.DeclaringType!.FullName);
vsb.Append('(');

bool first = true;

int count = ConstructorArguments.Count;
for (int i = 0; i < count; i++)
{
if (!first) vsb.Append(", ");
vsb.Append(ConstructorArguments[i].ToString());
first = false;
}

count = NamedArguments.Count;
for (int i = 0; i < count; i++)
{
if (!first) vsb.Append(", ");
vsb.Append(NamedArguments[i].ToString());
first = false;
}

string namedArgs = "";
for (int i = 0; i < NamedArguments.Count; i++)
namedArgs += string.Format(i == 0 && ctorArgs.Length == 0 ? "{0}" : ", {0}", NamedArguments[i]);
vsb.Append(")]");

return string.Format("[{0}({1}{2})]", Constructor.DeclaringType!.FullName, ctorArgs, namedArgs);
return vsb.ToString();
}
public override int GetHashCode() => base.GetHashCode();
public override bool Equals(object? obj) => obj == (object)this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -557,9 +557,6 @@ internal sealed class MetadataException : Exception
private int m_hr;
internal MetadataException(int hr) { m_hr = hr; }

public override string ToString()
{
return string.Format("MetadataException HResult = {0:x}.", m_hr);
}
public override string ToString() => $"MetadataException HResult = {m_hr:x}.";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ internal static unsafe string GetMessage(int errorCode, IntPtr moduleHandle)
}

// Couldn't get a message, so manufacture one.
return string.Format("Unknown error (0x{0:x})", errorCode);
return $"Unknown error (0x{errorCode:x})";
}

private static string GetAndTrimString(Span<char> buffer)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ internal static void ValidateSubprotocol(string subProtocol)
char ch = subProtocol[i];
if (ch < 0x21 || ch > 0x7e)
{
invalidChar = string.Format(CultureInfo.InvariantCulture, "[{0}]", (int)ch);
invalidChar = $"[{(int)ch}]";
break;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@ internal sealed class ComTypeEnumDesc : ComTypeDesc, IDynamicMetaObjectProvider
private readonly string[] _memberNames;
private readonly object[] _memberValues;

public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "<enum '{0}'>", TypeName);
}
public override string ToString() => $"<enum '{TypeName}'>";

internal ComTypeEnumDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc) :
base(typeInfo, typeLibDesc)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,7 @@ private ComTypeLibDesc()
_classes = new LinkedList<ComTypeClassDesc>();
}

public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "<type library {0}>", Name);
}
public override string ToString() => $"<type library {Name}>";

public string Documentation
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ internal DispCallable(IDispatchComObject dispatch, string memberName, int dispId
DispId = dispId;
}

public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "<bound dispmethod {0}>", MemberName);
}
public override string ToString() => $"<bound dispmethod {MemberName}>";

public IDispatchComObject DispatchComObject { get; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public override string ToString()
typeName = "IDispatch";
}

return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", RuntimeCallableWrapper.ToString(), typeName);
return $"{RuntimeCallableWrapper.ToString()} ({typeName})";
}

public ComTypeDesc ComTypeDesc
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,10 +281,7 @@ internal static System.Reflection.MethodInfo GetByrefSetter(VarEnum varType)
}
}

public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "Variant ({0})", VariantType);
}
public override string ToString() => $"Variant ({VariantType})";

public void SetAsIConvertible(IConvertible value)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public override void Load()
{
// "/SomeSwitch" is equivalent to "--SomeSwitch" when interpreting switch mappings
// So we do a conversion to simplify later processing
currentArg = string.Format("--{0}", currentArg.Substring(1));
currentArg = $"--{currentArg.Substring(1)}";
keyStartIndex = 2;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,7 @@ public override DirectoryInfoBase GetDirectory(string name)
{
// This shouldn't happen. The parameter name isn't supposed to contain wild card.
throw new InvalidOperationException(
string.Format("More than one sub directories are found under {0} with name {1}.",
_directoryInfo.FullName, name));
$"More than one sub directories are found under {_directoryInfo.FullName} with name {name}.");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ internal static string CombinePath(string left, string right)
}
else
{
return string.Format("{0}/{1}", left, right);
return $"{left}/{right}";
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public override string ToString()
string className = GetType().ToString();
StringBuilder s = new StringBuilder(className);
string nativeErrorString = NativeErrorCode < 0
? string.Format(CultureInfo.InvariantCulture, "0x{0:X8}", NativeErrorCode)
? $"0x{NativeErrorCode:X8}"
: NativeErrorCode.ToString(CultureInfo.InvariantCulture);
if (HResult == E_FAIL)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -668,9 +668,7 @@ private unsafe void Initialize()

IntPtr hInstance = Interop.Kernel32.GetModuleHandle(null);

s_className = string.Format(
".NET-BroadcastEventWindow.{0:x}.0",
AppDomain.CurrentDomain.GetHashCode());
s_className = $".NET-BroadcastEventWindow.{AppDomain.CurrentDomain.GetHashCode():x}.0";

fixed (char* className = s_className)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ private static Assembly LoadAssembly(string assemblyName, bool throwOnFail)
private void WriteHeader()
{
// do not localize Copyright header
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, ".NET Xml Serialization Generation Utility, Version {0}]", ThisAssembly.InformationalVersion));
Console.WriteLine($".NET Xml Serialization Generation Utility, Version {ThisAssembly.InformationalVersion}]");
}

private void WriteHelp()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ private string DebuggerDisplay
get
{
var self = this;
return self.IsDefault ? "Uninitialized" : string.Format(CultureInfo.CurrentCulture, "Length = {0}", self.Length);
return self.IsDefault ? "Uninitialized" : $"Length = {self.Length}";
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,14 +173,8 @@ private void ThrowIfDisposed()
}
}

private string GetDisplayName()
{
return string.Format(CultureInfo.CurrentCulture,
"{0} (Path=\"{1}\") (PrivateProbingPath=\"{2}\")", // NOLOC
GetType().Name,
AppDomain.CurrentDomain.BaseDirectory,
AppDomain.CurrentDomain.RelativeSearchPath);
}
private string GetDisplayName() =>
$"{GetType().Name} (Path=\"{AppDomain.CurrentDomain.BaseDirectory}\") (PrivateProbingPath=\"{AppDomain.CurrentDomain.RelativeSearchPath}\")"; // NOLOC

/// <summary>
/// Returns a string representation of the directory catalog.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -540,13 +540,8 @@ private void ThrowIfDisposed()
}
}

private string GetDisplayName()
{
return string.Format(CultureInfo.CurrentCulture,
"{0} (Assembly=\"{1}\")", // NOLOC
GetType().Name,
Assembly.FullName);
}
private string GetDisplayName() =>
$"{GetType().Name} (Assembly=\"{Assembly.FullName}\")"; // NOLOC

private static Assembly LoadAssembly(string codeBase)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -732,13 +732,8 @@ private void DiffChanges(string[] beforeFiles, string[] afterFiles,
}
}

private string GetDisplayName()
{
return string.Format(CultureInfo.CurrentCulture,
"{0} (Path=\"{1}\")", // NOLOC
GetType().Name,
_path);
}
private string GetDisplayName() =>
$"{GetType().Name} (Path=\"{_path}\")"; // NOLOC

private string[] GetFiles()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ internal static class MetadataViewGenerator

private static readonly Lock _lock = new Lock();
private static readonly Dictionary<Type, MetadataViewFactory> _metadataViewFactories = new Dictionary<Type, MetadataViewFactory>();
private static readonly AssemblyName ProxyAssemblyName = new AssemblyName(string.Format(CultureInfo.InvariantCulture, "MetadataViewProxies_{0}", Guid.NewGuid()));
private static readonly AssemblyName ProxyAssemblyName = new AssemblyName($"MetadataViewProxies_{Guid.NewGuid()}");
private static ModuleBuilder? transparentProxyModuleBuilder;

private static readonly Type[] CtorArgumentTypes = new Type[] { typeof(IDictionary<string, object>) };
Expand Down Expand Up @@ -193,7 +193,7 @@ private static void GenerateLocalAssignmentFromFlag(this ILGenerator IL, LocalBu

var proxyModuleBuilder = GetProxyModuleBuilder(requiresCritical);
proxyTypeBuilder = proxyModuleBuilder.DefineType(
string.Format(CultureInfo.InvariantCulture, "_proxy_{0}_{1}", viewType.FullName, Guid.NewGuid()),
$"_proxy_{viewType.FullName}_{Guid.NewGuid()}",
TypeAttributes.Public,
typeof(object),
interfaces);
Expand All @@ -214,7 +214,7 @@ private static void GenerateLocalAssignmentFromFlag(this ILGenerator IL, LocalBu
// Implement interface properties
foreach (PropertyInfo propertyInfo in viewType.GetAllProperties())
{
string fieldName = string.Format(CultureInfo.InvariantCulture, "_{0}_{1}", propertyInfo.Name, Guid.NewGuid());
string fieldName = $"_{propertyInfo.Name}_{Guid.NewGuid()}";

// Cache names and type for exception
string propertyName = propertyInfo.Name;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -371,19 +371,19 @@ public override string ToString()
{
var sb = new StringBuilder();

sb.Append(string.Format("\n\tContractName\t{0}", ContractName));
sb.Append(string.Format("\n\tRequiredTypeIdentity\t{0}", RequiredTypeIdentity));
sb.Append("\n\tContractName\t").Append(ContractName);
sb.Append("\n\tRequiredTypeIdentity\t").Append(RequiredTypeIdentity);
if (_requiredCreationPolicy != CreationPolicy.Any)
{
sb.Append(string.Format("\n\tRequiredCreationPolicy\t{0}", RequiredCreationPolicy));
sb.Append("\n\tRequiredCreationPolicy\t").Append(RequiredCreationPolicy);
}

if (_requiredMetadata.Any())
{
sb.Append("\n\tRequiredMetadata");
foreach (KeyValuePair<string, Type> metadataItem in _requiredMetadata)
{
sb.Append(string.Format("\n\t\t{0}\t({1})", metadataItem.Key, metadataItem.Value));
sb.Append("\n\t\t").Append(metadataItem.Key).Append("\t(").Append(metadataItem.Value).Append(')');
}
}
return sb.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,7 @@ private ReflectionMember ToReflectionMember()
return ExportingLazyMember.ToReflectionMember();
}

private string GetDisplayName()
{
return string.Format(CultureInfo.CurrentCulture,
"{0} (ContractName=\"{1}\")", // NOLOC
ToReflectionMember().GetDisplayName(),
ContractName);
}
private string GetDisplayName() =>
$"{ToReflectionMember().GetDisplayName()} (ContractName=\"{ContractName}\")"; // NOLOC
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,7 @@ public LazyMemberInfo ImportingLazyMember
get { return _importingLazyMember; }
}

protected override string GetDisplayName()
{
return string.Format(
CultureInfo.CurrentCulture,
"{0} (ContractName=\"{1}\")", // NOLOC
ImportingLazyMember.ToReflectionMember().GetDisplayName(),
ContractName);
}
protected override string GetDisplayName() =>
$"{ImportingLazyMember.ToReflectionMember().GetDisplayName()} (ContractName=\"{ContractName}\")"; // NOLOC
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,8 @@ public override string? Name
get { return UnderlyingParameter.Name; }
}

public override string GetDisplayName()
{
return string.Format(
CultureInfo.CurrentCulture,
"{0} (Parameter=\"{1}\")", // NOLOC
UnderlyingParameter.Member.GetDisplayName(),
UnderlyingParameter.Name);
}
public override string GetDisplayName() =>
$"{UnderlyingParameter.Member.GetDisplayName()} (Parameter=\"{UnderlyingParameter.Name}\")"; // NOLOC

public override Type ReturnType
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,7 @@ public Lazy<ParameterInfo> ImportingLazyParameter
protected override string GetDisplayName()
{
ParameterInfo parameter = ImportingLazyParameter.GetNotNullValue("parameter");
return string.Format(
CultureInfo.CurrentCulture,
"{0} (Parameter=\"{1}\", ContractName=\"{2}\")", // NOLOC
parameter.Member.GetDisplayName(),
parameter.Name,
ContractName);
return $"{parameter.Member.GetDisplayName()} (Parameter=\"{parameter.Name}\", ContractName=\"{ContractName}\")"; // NOLOC
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ private static string FormatClosedGeneric(Type closedGenericType)

var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf('`'));
var args = closedGenericType.GenericTypeArguments.Select(t => Format(t));
return string.Format("{0}<{1}>", name, string.Join(", ", args));
return $"{name}<{string.Join(", ", args)}>";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ public override string ToString()
if (_metadataConstraints != null)
result += string.Format(" {{ {0} }}",
string.Join(SR.Formatter_ListSeparatorWithSpace,
_metadataConstraints.Select(kv => string.Format("{0} = {1}", kv.Key, Formatters.Format(kv.Value)))));
_metadataConstraints.Select(kv => $"{kv.Key} = {Formatters.Format(kv.Value)}")));

return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ private static string FormatClosedGeneric(Type closedGenericType)
Debug.Assert(closedGenericType.IsConstructedGenericType);
var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf('`'));
IEnumerable<string> args = closedGenericType.GenericTypeArguments.Select(t => Format(t));
return string.Format("{0}<{1}>", name, string.Join(SR.Formatter_ListSeparatorWithSpace, args));
return $"{name}<{string.Join(SR.Formatter_ListSeparatorWithSpace, args)}>";
}
}
}
Loading

0 comments on commit 0c79392

Please sign in to comment.