Original file line number Diff line number Diff line change
Expand Up @@ -707,9 +707,9 @@ internal bool GrabChunk(KeyValuePair<long, TSource>[] destArray, int requestedCh
internal bool GrabChunk_Single(KeyValuePair<long, TSource>[] 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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public static string GetGenericName(string originalGenericName, int[] genericPar
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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,6 @@ public override bool Equals([NotNullWhen(true)] object? obj)
/// <summary>
/// Overrides Object's ToString method.
/// </summary>
public override string ToString() => Guid.ToString() + " : " + ID.ToString(CultureInfo.CurrentCulture);
public override string ToString() => $"{Guid} : {ID}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1114,7 +1114,7 @@ internal static Attribute[] ReflectGetAttributes(MemberInfo member)
#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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ internal int AppendEntityRef(string entityRef)

internal int AppendCharEntity(char ch)
{
string numberToWrite = ((int)ch).ToString("X", CultureInfo.InvariantCulture);
string numberToWrite = ((int)ch).ToString("X");
Write('&');
Write('#');
Write('x');
Expand Down
5 changes: 3 additions & 2 deletions src/libraries/System.Console/src/System/TermInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -245,9 +245,10 @@ private static bool TryOpen(string filePath, [NotNullWhen(true)] out SafeFileHan
return null;
}

Span<char> 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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ public virtual ICollection Values
{
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<object>(values);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ public static string UniqueConstraintViolationText(DataColumn[] columns, object[
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);


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ internal override void Bind(DataTable table, List<DataColumn> list)

// 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++)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ private object EvalFunction(FunctionId id, object[] argumentValues, DataRow? row
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))
Expand All @@ -329,7 +329,7 @@ private object EvalFunction(FunctionId id, object[] argumentValues, DataRow? row
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
Expand All @@ -341,26 +341,26 @@ private object EvalFunction(FunctionId id, object[] argumentValues, DataRow? row
_ => 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;
Expand All @@ -374,7 +374,7 @@ private object EvalFunction(FunctionId id, object[] argumentValues, DataRow? row
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);

Expand All @@ -401,8 +401,8 @@ private object EvalFunction(FunctionId id, object[] argumentValues, DataRow? row
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)
{
Expand All @@ -420,10 +420,10 @@ private object EvalFunction(FunctionId id, object[] argumentValues, DataRow? row


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 <index> Argument is 0-based in .NET, and 1-based in VBA
Expand Down Expand Up @@ -462,8 +462,8 @@ private object EvalFunction(FunctionId id, object[] argumentValues, DataRow? row

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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ internal override void Bind(DataTable table, List<DataColumn> list)
_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++)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ internal void CheckCanClearParentTable(DataTable table)

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;
Expand All @@ -517,7 +517,7 @@ internal void CheckCanRemoveParentRow(DataRow row)

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)
{
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Data.Common/src/System/Data/Merger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,7 @@ private void MergeRelation(DataRelation relation)
}
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);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,7 @@ public int Length
/// <summary>
/// Returns a string describing a <see cref='SqlBinary'/> object.
/// </summary>
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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1911,7 +1911,7 @@ private bool FGt10_38()

private bool FGt10_38(Span<uint> 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) ||
Expand Down
6 changes: 3 additions & 3 deletions src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ internal void LoadSchema(XmlElement schemaRoot, DataSet ds)

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)
Expand Down Expand Up @@ -282,12 +282,12 @@ private static NameType FindNameType(string name)
// 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];
}

Expand Down
10 changes: 5 additions & 5 deletions src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1790,7 +1790,7 @@ public static Type XsdtoClr(string xsdTypeName)
#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);
Expand Down Expand Up @@ -1856,7 +1856,7 @@ private static NameType FindNameType(string name)
#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);
Expand Down Expand Up @@ -1904,7 +1904,7 @@ internal static bool IsXsdType(string name)
#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);
Expand All @@ -1914,12 +1914,12 @@ internal static bool IsXsdType(string name)
// 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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1295,7 +1295,7 @@ internal void HandleColumnType(DataColumn col, XmlDocument dc, XmlElement root,
{
#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
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ public void GetXml()

StringBuilder resultXML = new StringBuilder();

resultXML.Append("<" + ds.DataSetName + "xmlns=\"namespace\">");
resultXML.Append($"<{ds.DataSetName}xmlns=\"namespace\">");

resultXML.Append("<Parent>");
resultXML.Append("<ParentId>1</ParentId>");
Expand All @@ -455,7 +455,7 @@ public void GetXml()
resultXML.Append("<String2>Value5</String2>");
resultXML.Append("</Parent>");

resultXML.Append("</" + ds.DataSetName + ">");
resultXML.Append($"</{ds.DataSetName}>");

ds.Tables.Add(dt);
string strXML = ds.GetXml();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ private int GetParameterSize(object? value, int offset, int ordinal)
}
}
}
Debug.Assert((0 <= ccb) && (ccb < 0x3fffffff), "GetParameterSize: out of range " + ccb);
Debug.Assert((0 <= ccb) && (ccb < 0x3fffffff), $"GetParameterSize: out of range {ccb}");
return ccb;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,7 @@ public static bool AreConnStringsSetup()
// 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;
}

Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Data.OleDb/src/ColumnBinding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ internal sealed class ColumnBinding
{
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;
Expand Down
8 changes: 4 additions & 4 deletions src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -844,8 +844,8 @@ private static void ParseComparison(Hashtable parsetable, string connectionStrin
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}>");
}

}
Expand All @@ -871,11 +871,11 @@ private static void ParseComparison(Hashtable parsetable, string connectionStrin
}
}
}
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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Data.OleDb/src/DbPropSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ internal void SetPropertySet(int index, Guid propertySet, ItagDBPROP[] propertie

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*/);
}
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Data.OleDb/src/OleDbConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ public void ResetState()
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;
}
}
Expand Down
18 changes: 9 additions & 9 deletions src/libraries/System.Data.OleDb/src/OleDbDataReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ private void BuildSchemaTableInfoTable(int columnCount, IntPtr columnInfos, bool
#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++;
Expand Down Expand Up @@ -2108,7 +2108,7 @@ private int AppendSchemaPrimaryKey(Hashtable baseColumnNames, object?[] restrict
#if DEBUG
if (AdapterSwitches.DataSchema.TraceVerbose)
{
Debug.WriteLine("PartialKeyColumn detected: <" + name + "> metaindex=" + metaindex);
Debug.WriteLine($"PartialKeyColumn detected: <{name}> metaindex={metaindex}");
}
#endif
partialPrimaryKey = true;
Expand Down Expand Up @@ -2199,7 +2199,7 @@ private void AppendSchemaUniqueIndexAsKey(Hashtable baseColumnNames, object?[] r
#if DEBUG
if (AdapterSwitches.DataSchema.TraceVerbose)
{
Debug.WriteLine("MultipleUniqueIndexes detected: <" + uniqueIndexName + "> <" + indexname + ">");
Debug.WriteLine($"MultipleUniqueIndexes detected: <{uniqueIndexName}> <{indexname}>");
}
#endif
uniq = null;
Expand All @@ -2211,7 +2211,7 @@ private void AppendSchemaUniqueIndexAsKey(Hashtable baseColumnNames, object?[] r
#if DEBUG
if (AdapterSwitches.DataSchema.TraceVerbose)
{
Debug.WriteLine("PartialKeyColumn detected: " + name);
Debug.WriteLine($"PartialKeyColumn detected: {name}");
}
#endif
partialPrimaryKey = true;
Expand All @@ -2226,7 +2226,7 @@ private void AppendSchemaUniqueIndexAsKey(Hashtable baseColumnNames, object?[] r
#if DEBUG
if (AdapterSwitches.DataSchema.TraceVerbose)
{
Debug.WriteLine("PartialUniqueIndexes detected: <" + uniqueIndexName + "> <" + indexname + ">");
Debug.WriteLine($"PartialUniqueIndexes detected: <{uniqueIndexName}> <{indexname}>");
}
#endif
uniq = null;
Expand All @@ -2247,7 +2247,7 @@ private void AppendSchemaUniqueIndexAsKey(Hashtable baseColumnNames, object?[] r
#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
Expand Down Expand Up @@ -2498,7 +2498,7 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset)
#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;
Expand All @@ -2509,7 +2509,7 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset)
#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;
Expand All @@ -2520,7 +2520,7 @@ internal void DumpToSchemaTable(UnsafeNativeMethods.IRowset? rowset)
#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;
Expand Down
52 changes: 26 additions & 26 deletions src/libraries/System.Data.OleDb/src/OleDbStruct.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@ public override string ToString()
{
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
Expand All @@ -78,12 +78,12 @@ public override string ToString()
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
Expand Down Expand Up @@ -144,15 +144,15 @@ internal tagDBBINDING()
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
Expand Down Expand Up @@ -442,14 +442,14 @@ internal tagDBCOLUMNINFO()
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
Expand Down
8 changes: 2 additions & 6 deletions src/libraries/System.Data.OleDb/src/OleDb_Util.cs
Original file line number Diff line number Diff line change
Expand Up @@ -697,9 +697,7 @@ internal static string ELookup(OleDbHResult hr)
{
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();
}

Expand All @@ -710,9 +708,7 @@ internal static string WLookup(short id)
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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ internal static ArgumentOutOfRangeException InvalidCommandType(CommandType value
case CommandType.Text:
case CommandType.StoredProcedure:
case CommandType.TableDirect:
Debug.Assert(false, "valid CommandType " + value.ToString());
Debug.Assert(false, $"valid CommandType {value}");
break;
}
#endif
Expand All @@ -283,7 +283,7 @@ internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion
case DataRowVersion.Current:
case DataRowVersion.Original:
case DataRowVersion.Proposed:
Debug.Assert(false, "valid DataRowVersion " + value.ToString());
Debug.Assert(false, $"valid DataRowVersion {value}");
break;
}
#endif
Expand All @@ -303,7 +303,7 @@ internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel
case IsolationLevel.RepeatableRead:
case IsolationLevel.Serializable:
case IsolationLevel.Snapshot:
Debug.Assert(false, "valid IsolationLevel " + value.ToString());
Debug.Assert(false, $"valid IsolationLevel {value}");
break;
}
#endif
Expand All @@ -320,7 +320,7 @@ internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterD
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
Debug.Assert(false, "valid ParameterDirection " + value.ToString());
Debug.Assert(false, $"valid ParameterDirection {value}");
break;
}
#endif
Expand All @@ -337,7 +337,7 @@ internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSour
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
Debug.Assert(false, $"valid UpdateRowSource {value}");
break;
}
#endif
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ private unsafe FileVersionInfo(string fileName)

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)
Expand Down Expand Up @@ -126,18 +126,20 @@ private static uint GetVarEntry(IntPtr memPtr)
//
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<char> 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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ internal void EnsureWriter()
}
catch (IOException)
{
fileNameOnly = Guid.NewGuid().ToString() + fileNameOnly;
fileNameOnly = $"{Guid.NewGuid()}{fileNameOnly}";
fullPath = Path.Combine(dirPath, fileNameOnly);
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ public virtual void Close()

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}"));
}

/// <devdoc>
Expand All @@ -201,8 +201,8 @@ public virtual void Fail(string? message)
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}");
}

/// <devdoc>
Expand Down Expand Up @@ -390,7 +390,7 @@ public virtual void TraceEvent(TraceEventCache? eventCache, string source, Trace

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)
Expand Down Expand Up @@ -425,14 +425,16 @@ private void WriteFooter(TraceEventCache? eventCache)
WriteLine(string.Empty);
}

Span<char> 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ protected virtual void Dispose(bool disposing)
#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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ private void Dispose(bool disposing)
#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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ private void Dispose(bool disposing)
#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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ protected override bool ReleaseHandle()
{
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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ private void CreateFont(string familyName, float emSize, FontStyle style, Graphi
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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ private void Dispose(bool disposing)
#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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina

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)
Expand Down Expand Up @@ -79,7 +80,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina

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());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ private void Dispose(bool disposing)
#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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ private void Dispose(bool disposing)
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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ protected virtual void Dispose(bool disposing)
#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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public override string ToString()
if (this == s_time) return "Time";
if (this == s_resolution) return "Resolution";
if (this == s_page) return "Page";
return "[FrameDimension: " + _guid + "]";
return $"[FrameDimension: {_guid}]";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ private void Dispose(bool disposing)
#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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public override string ToString()
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}]";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ internal static void Add(ISystemColorTracker obj)
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;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ private void Dispose(bool disposing)
#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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,14 +235,6 @@ public override bool Equals([NotNullWhen(true)] object? obj)
/// <summary>
/// Provides some interesting information for the Margins in String form.
/// </summary>
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}]";
333fred marked this conversation as resolved.
Show resolved Hide resolved
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,7 @@ public void SetHdevmode(IntPtr hdevmode)
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}]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -536,16 +536,7 @@ public void SetHdevmode(IntPtr hdevmode)
/// <summary>
/// Provides some interesting information about the PageSettings in String form.
/// </summary>
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}]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,6 @@ public int Width
/// <summary>
/// Provides some interesting information about the PaperSize in String form.
/// </summary>
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)}]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,6 @@ public string SourceName
/// <summary>
/// Provides some interesting information about the PaperSource in String form.
/// </summary>
public override string ToString()
{
return "[PaperSource " + SourceName
+ " Kind=" + Kind.ToString()
+ "]";
}
public override string ToString() => $"[PaperSource {SourceName} Kind={Kind}]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,7 @@ public void Print()
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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,9 +248,6 @@ public void Print()
/// <summary>
/// Provides some interesting information about the PrintDocument in String form.
/// </summary>
public override string ToString()
{
return "[PrintDocument " + DocumentName + "]";
}
public override string ToString() => $"[PrintDocument {DocumentName}]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -365,13 +365,7 @@ public void SetHdevnames(IntPtr hdevnames)
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1258,16 +1258,16 @@ public override string ToString()
{
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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ private void Dispose(bool disposing)
#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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ private void Dispose(bool disposing)
#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)
Expand Down Expand Up @@ -442,9 +442,6 @@ internal int GetMeasurableCharacterRangeCount()
/// <summary>
/// Converts this <see cref='StringFormat'/> to a human-readable string.
/// </summary>
public override string ToString()
{
return "[StringFormat, FormatFlags=" + FormatFlags.ToString() + "]";
}
public override string ToString() => $"[StringFormat, FormatFlags={FormatFlags.ToString()}]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ protected override void Dispose(bool disposing)
#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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -565,21 +565,10 @@ public float GetSaturation()

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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public void Offset(int dx, int dy)
/// <summary>
/// Converts this <see cref='System.Drawing.Point'/> to a human readable string.
/// </summary>
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));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,6 @@ public float Y

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}}}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -340,8 +340,6 @@ public void Offset(int x, int y)
/// <summary>
/// Converts the attributes of this <see cref='System.Drawing.Rectangle'/> to a human readable string.
/// </summary>
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}}}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -326,8 +326,6 @@ public void Offset(float x, float y)
/// Converts the <see cref='System.Drawing.RectangleF.Location'/> and <see cref='System.Drawing.RectangleF.Size'/>
/// of this <see cref='System.Drawing.RectangleF'/> to a human-readable string.
/// </summary>
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}}}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public int Height
/// <summary>
/// Creates a human-readable string that represents this <see cref='System.Drawing.Size'/>.
/// </summary>
public override readonly string ToString() => "{Width=" + width.ToString() + ", Height=" + height.ToString() + "}";
public override readonly string ToString() => $"{{Width={width}, Height={height}}}";

/// <summary>
/// Multiplies <see cref="Size"/> by an <see cref="int"/> producing <see cref="Size"/>.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ public float Height
/// <summary>
/// Creates a human-readable string that represents this <see cref='System.Drawing.SizeF'/>.
/// </summary>
public override readonly string ToString() => "{Width=" + width.ToString() + ", Height=" + height.ToString() + "}";
public override readonly string ToString() => $"{{Width={width}, Height={height}}}";

/// <summary>
/// Multiplies <see cref="SizeF"/> by a <see cref="float"/> producing <see cref="SizeF"/>.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ public void VerifyWriteInteger_Context9_ULong(AsnEncodingRules ruleSet, ulong va
[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());
Expand All @@ -298,7 +298,7 @@ public void VerifyWriteInteger_EncodedBytes(string valueHex)
[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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,7 @@ private static string DumpStringAsCodepoints(string s)
StringBuilder sb = new StringBuilder();
for (int i=0; i<s.Length; i++)
{
sb.Append("\\x");
sb.Append(((int)s[i]).ToString("X4"));
sb.Append($"\\x{(int)s[i]:X4}");
}
return sb.ToString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public void GetNumericValue_Invalid()

private static string ErrorMessage(char ch, object expected, object actual)
{
return $"CodeValue: {((int)ch).ToString("X")}; Expected: {expected}; Actual: {actual}";
return $"CodeValue: {(int)ch:X}; Expected: {expected}; Actual: {actual}";
}

public static string s_numericsCodepoints =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ private void CreateFileSystem()
for (int k = 0; k < numOfDirPerDir; k++)
{
string dirName = GetNonExistingDir(dir, DirPrefixName);
Debug.Assert(!Directory.Exists(dirName), string.Format("ERR_93472g! Directory exists: {0}", dirName));
Debug.Assert(!Directory.Exists(dirName), $"ERR_93472g! Directory exists: {dirName}");
tempDirsForOneLevel.Add(dirName, new List<string>());
_listOfAllDirs.Add(dirName);
Directory.CreateDirectory(dirName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ internal static string ToHexString(ReadOnlySpan<byte> input)

foreach (byte b in input)
{
builder.Append(b.ToString("X2"));
builder.Append($"{b:X2}");
}

return builder.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ protected void InitStore(IsolatedStorageScope scope, Type? domainEvidenceType, T
if (Helper.IsDomain(scope))
{
_domainIdentity = identity;
hash = $"{hash}{SeparatorExternal}{hash}";
hash = string.Create(null, stackalloc char[128], $"{hash}{SeparatorExternal}{hash}");
}

_assemblyIdentity = identity;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ private static FileStream CreateSharedBackingObject(Interop.Sys.MemoryMappedProt
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 ?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public PooledMemory(IMemoryOwner<byte> owner, TestMemoryPool pool)

~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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ private void Cancel()

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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1005,7 +1005,7 @@ internal unsafe int Read(byte[] array, int offset, int count, int timeout)

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)
Expand Down Expand Up @@ -1069,7 +1069,7 @@ internal unsafe void Write(byte[] array, int offset, int count, int timeout)

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)
Expand Down Expand Up @@ -1627,7 +1627,7 @@ internal unsafe void WaitForCommEvent()
// 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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ static string PortInformationString
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();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,8 @@ public RuntimeLabel(int index, int continuationStackDepth, int stackDepth)
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,15 +195,15 @@ private void UpdateStackDepth(Instruction instruction)
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)
{
_maxStackDepth = _currentStackDepth;
}

_currentContinuationsDepth -= instruction.ConsumedContinuations;
Debug.Assert(_currentContinuationsDepth >= 0, "negative continuations " + instruction.ToString());
Debug.Assert(_currentContinuationsDepth >= 0, $"negative continuations {instruction}");
_currentContinuationsDepth += instruction.ProducedContinuations;
if (_currentContinuationsDepth > _maxContinuationDepth)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ internal ExceptionHandler(int labelIndex, int handlerStartIndex, int handlerEndI
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
Expand Down Expand Up @@ -251,11 +251,11 @@ public override string ToString()
{
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}'");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public override string ToString()

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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,8 @@ internal LocalVariable(int index, bool closure)
_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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,8 @@ public override int Run(InterpretedFrame frame)
return 1;
}

public override string ToDebugString(int instructionIndex, object? cookie, Func<int, int> labelIndexer, IReadOnlyList<object>? objects)
{
return string.Format(CultureInfo.InvariantCulture, "LoadCached({0}: {1})", _index, objects![(int)_index]);
}
public override string ToDebugString(int instructionIndex, object? cookie, Func<int, int> labelIndexer, IReadOnlyList<object>? objects) =>
string.Create(CultureInfo.InvariantCulture, $"LoadCached({_index}: {objects![(int)_index]})");

public override string ToString() => "LoadCached(" + _index + ")";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ private void Dispose(bool disposing)
#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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static void TraceCallbackStatus(object thisOrContextObject, IntPtr handle

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);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,12 @@ public override string ToString()
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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ public override string ToString()
{
// 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}");
}
}

Expand All @@ -222,7 +222,7 @@ public override string ToString()
{
// 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}");
}
}

Expand All @@ -241,7 +241,7 @@ public override string ToString()
{
// 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}");
}
}
}
Expand All @@ -259,7 +259,7 @@ public override string ToString()
{
// 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}");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ internal bool RemoveParsedValue(HeaderDescriptor descriptor, object value)
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,20 @@ internal RangeItemHeaderValue(RangeItemHeaderValue source)

public override string ToString()
{
Span<char> 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public override string ToString()
{
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public override string ToString()
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);
Expand Down
24 changes: 10 additions & 14 deletions src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,35 +80,31 @@ private static void AssertEncodingConstants(Encoding encoding, int codePage, int
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ private static async Task<HttpResponseMessage> SendWithNtAuthAsync(HttpRequestMe

if (!isProxyAuth && !authUri.IsDefaultPort)
{
hostName = $"{hostName}:{authUri.Port}";
hostName = string.Create(null, stackalloc char[128], $"{hostName}:{authUri.Port}");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net.Http.Headers;
using System.Net.Security;

Expand Down Expand Up @@ -78,7 +79,7 @@ public Http3Connection(HttpConnectionPool pool, HttpAuthority? origin, HttpAutho
_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().
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -349,15 +349,12 @@ public byte[] Http2AltSvcOriginUri
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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,23 @@ public class HttpListenerException : Win32Exception
{
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,7 @@ private void BuildRequestUriUsingRawPath()

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)
{
Expand Down Expand Up @@ -330,8 +329,7 @@ private static void AppendOctetsPercentEncoded(StringBuilder target, IEnumerable
{
foreach (byte octet in octets)
{
target.Append('%');
target.Append(octet.ToString("X2", CultureInfo.InvariantCulture));
target.Append($"%{octet:X2}");
}
}

Expand All @@ -350,7 +348,7 @@ private static string GetOctetsAsString(IEnumerable<byte> octets)
{
octetString.Append(' ');
}
octetString.Append(octet.ToString("X2", CultureInfo.InvariantCulture));
octetString.Append($"{octet:X2}");
}

return octetString.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -962,7 +962,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult)
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(
Expand Down Expand Up @@ -1881,7 +1881,7 @@ private static unsafe void IOCompleted(DisconnectAsyncResult asyncResult, uint e

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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ internal void IOCompleted(uint errorCode, uint numBytes)

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
{
Expand All @@ -333,7 +333,7 @@ private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlap
{
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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ internal void IOCompleted(uint errorCode, uint numBytes)

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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ internal uint QueueBeginGetContext()
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!;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,15 +137,6 @@ internal static partial class HttpWebSocket
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
Expand Down