Skip to content

Commit

Permalink
Apply IDE0300 to corelib (use collection expressions instead of new[]) (
Browse files Browse the repository at this point in the history
  • Loading branch information
stephentoub authored Jul 19, 2024
1 parent 72f9ee0 commit 6068519
Show file tree
Hide file tree
Showing 81 changed files with 247 additions and 275 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -756,7 +756,7 @@ public LicenseInteropProxy()

Type licContext = Type.GetType("System.ComponentModel.LicenseContext, System.ComponentModel.TypeConverter", throwOnError: true)!;
_setSavedLicenseKey = licContext.GetMethod("SetSavedLicenseKey", BindingFlags.Instance | BindingFlags.Public)!;
_createWithContext = licManager.GetMethod("CreateWithContext", new[] { typeof(Type), licContext })!;
_createWithContext = licManager.GetMethod("CreateWithContext", [typeof(Type), licContext])!;

Type interopHelper = licManager.GetNestedType("LicenseInteropHelper", BindingFlags.NonPublic)!;
_validateTypeAndReturnDetails = interopHelper.GetMethod("ValidateAndRetrieveLicenseDetails", BindingFlags.Static | BindingFlags.Public)!;
Expand Down Expand Up @@ -816,7 +816,7 @@ public void GetLicInfo(Type type, out bool runtimeKeyAvail, out bool licVerified
licVerified = true;
}

parameters = new object?[] { type.AssemblyQualifiedName };
parameters = [type.AssemblyQualifiedName];
runtimeKeyAvail = (bool)_licInfoHelperContains.Invoke(licContext, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null)!;
}

Expand Down Expand Up @@ -867,18 +867,18 @@ public object AllocateAndValidateLicense([DynamicallyAccessedMembers(Dynamically
object? licContext;
if (isDesignTime)
{
parameters = new object[] { type };
parameters = [type];
licContext = _createDesignContext.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null);
}
else
{
parameters = new object?[] { type, key };
parameters = [type, key];
licContext = _createRuntimeContext.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null);
}

try
{
parameters = new object?[] { type, licContext };
parameters = [type, licContext];
return _createWithContext.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null)!;
}
catch (Exception exception) when (exception.GetType() == s_licenseExceptionType)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,12 @@ internal void InitializeSourceInfo(int iSkip, bool fNeedFileInfo, Exception? exc
return;
}

Type[] parameterTypes = new Type[]
{
Type[] parameterTypes =
[
typeof(Assembly), typeof(string), typeof(IntPtr), typeof(int), typeof(bool), typeof(IntPtr),
typeof(int), typeof(int), typeof(int),
typeof(string).MakeByRefType(), typeof(int).MakeByRefType(), typeof(int).MakeByRefType()
};
];
MethodInfo? symbolsMethodInfo = symbolsType.GetMethod("GetSourceLineInfo", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, parameterTypes, null);
if (symbolsMethodInfo == null)
{
Expand Down
4 changes: 2 additions & 2 deletions src/coreclr/System.Private.CoreLib/src/System/Enum.CoreCLR.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ private unsafe CorElementType InternalGetCorElementType()

// Indexed by CorElementType
private static readonly RuntimeType?[] s_underlyingTypes =
{
[
null,
null,
(RuntimeType)typeof(bool),
Expand All @@ -60,7 +60,7 @@ private unsafe CorElementType InternalGetCorElementType()
null,
(RuntimeType)typeof(nint),
(RuntimeType)typeof(nuint)
};
];

[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe RuntimeType InternalGetUnderlyingType(RuntimeType enumType)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -383,11 +383,10 @@ private void Init(TypeForwardedToAttribute forwardedTo)
{
Type type = typeof(TypeForwardedToAttribute);

Type[] sig = new Type[] { typeof(Type) };
Type[] sig = [typeof(Type)];
m_ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, sig, null)!;

CustomAttributeTypedArgument[] typedArgs = new CustomAttributeTypedArgument[1];
typedArgs[0] = new CustomAttributeTypedArgument(typeof(Type), forwardedTo.Destination);
CustomAttributeTypedArgument[] typedArgs = [new CustomAttributeTypedArgument(typeof(Type), forwardedTo.Destination)];
m_typedCtorArgs = Array.AsReadOnly(typedArgs);

m_namedArgs = Array.Empty<CustomAttributeNamedArgument>();
Expand Down Expand Up @@ -1954,8 +1953,8 @@ internal static class PseudoCustomAttribute
#region Static Constructor
private static HashSet<RuntimeType> CreatePseudoCustomAttributeHashSet()
{
Type[] pcas = new Type[]
{
Type[] pcas =
[
// See https://github.com/dotnet/runtime/blob/main/src/coreclr/md/compiler/custattr_emit.cpp
typeof(FieldOffsetAttribute), // field
typeof(SerializableAttribute), // class, struct, enum, delegate
Expand All @@ -1968,7 +1967,7 @@ private static HashSet<RuntimeType> CreatePseudoCustomAttributeHashSet()
typeof(DllImportAttribute), // method
typeof(PreserveSigAttribute), // method
typeof(TypeForwardedToAttribute), // assembly
};
];

HashSet<RuntimeType> set = new HashSet<RuntimeType>(pcas.Length);
foreach (RuntimeType runtimeType in pcas)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public T[] ToArray()
if (_count == 0)
return Array.Empty<T>();
if (_count == 1)
return new T[1] { _item };
return [_item];

Array.Resize(ref _items, _count);
_capacity = _count;
Expand Down Expand Up @@ -3569,7 +3569,7 @@ public override Type MakeGenericType(Type[] instantiation)
}
catch (TypeLoadException e)
{
ValidateGenericArguments(this, new[] { rt }, e);
ValidateGenericArguments(this, [rt], e);
throw;
}
}
Expand Down Expand Up @@ -4036,7 +4036,7 @@ private extern object InvokeDispMethod(
paramMod[i] = aArgsIsByRef[i];
}

aParamMod = new ParameterModifier[] { paramMod };
aParamMod = [paramMod];
if (aArgsWrapperTypes != null)
{
WrapArgsForInvokeCall(aArgs, aArgsWrapperTypes);
Expand Down Expand Up @@ -4124,23 +4124,23 @@ private static void WrapArgsForInvokeCall(object[] aArgs, int[] aArgsWrapperType
ConstructorInfo wrapperCons;
if (isString)
{
wrapperCons = wrapperType.GetConstructor(new Type[] { typeof(string) })!;
wrapperCons = wrapperType.GetConstructor([typeof(string)])!;
}
else
{
wrapperCons = wrapperType.GetConstructor(new Type[] { typeof(object) })!;
wrapperCons = wrapperType.GetConstructor([typeof(object)])!;
}

// Wrap each of the elements of the array.
for (int currElem = 0; currElem < numElems; currElem++)
{
if (isString)
{
newArray[currElem] = wrapperCons.Invoke(new object?[] { (string?)oldArray.GetValue(currElem) });
newArray[currElem] = wrapperCons.Invoke([(string?)oldArray.GetValue(currElem)]);
}
else
{
newArray[currElem] = wrapperCons.Invoke(new object?[] { oldArray.GetValue(currElem) });
newArray[currElem] = wrapperCons.Invoke([oldArray.GetValue(currElem)]);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ private object CreateEventProvider(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] RuntimeType t)
{
// Create the event provider for the specified type.
object EvProvider = Activator.CreateInstance(t, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, new object[] { this }, null)!;
object EvProvider = Activator.CreateInstance(t, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, [this], null)!;

// Attempt to cache the wrapper on the object.
if (!SetData(t, EvProvider))
Expand Down
20 changes: 10 additions & 10 deletions src/libraries/Common/src/System/Number.Formatting.Common.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,37 +20,37 @@ internal static partial class Number
private const string PosNumberFormat = "#";

private static readonly string[] s_posCurrencyFormats =
{
[
"$#", "#$", "$ #", "# $"
};
];

private static readonly string[] s_negCurrencyFormats =
{
[
"($#)", "-$#", "$-#", "$#-",
"(#$)", "-#$", "#-$", "#$-",
"-# $", "-$ #", "# $-", "$ #-",
"$ -#", "#- $", "($ #)", "(# $)",
"$- #"
};
];

private static readonly string[] s_posPercentFormats =
{
[
"# %", "#%", "%#", "% #"
};
];

private static readonly string[] s_negPercentFormats =
{
[
"-# %", "-#%", "-%#",
"%-#", "%#-",
"#-%", "#%-",
"-% #", "# %-", "% #-",
"% -#", "#- %"
};
];

private static readonly string[] s_negNumberFormats =
{
[
"(#)", "-#", "- #", "#-", "# -",
};
];

internal static unsafe char ParseFormatSpecifier(ReadOnlySpan<char> format, out int digits)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public DelegateWrapper(Delegate d, bool wrapArgs)
}
}

return Delegate.DynamicInvoke(WrapArgs ? new object[] { args } : args);
return Delegate.DynamicInvoke(WrapArgs ? [args] : args);
}

private void PreProcessSignature()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public AggregateException(string? message, Exception innerException)
{
ArgumentNullException.ThrowIfNull(innerException);

_innerExceptions = new[] { innerException };
_innerExceptions = [innerException];
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ private static int ExecuteAssembly(Assembly assembly, string?[]? args)
obj: null,
invokeAttr: BindingFlags.DoNotWrapExceptions,
binder: null,
parameters: entry.GetParametersAsSpan().Length > 0 ? new object?[] { args } : null,
parameters: entry.GetParametersAsSpan().Length > 0 ? [args] : null,
culture: null);

return result != null ? (int)result : 0;
Expand Down
4 changes: 2 additions & 2 deletions src/libraries/System.Private.CoreLib/src/System/Array.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1065,9 +1065,9 @@ public void CopyTo(Array array, long index)

private static class EmptyArray<T>
{
#pragma warning disable CA1825 // this is the implementation of Array.Empty<T>()
#pragma warning disable CA1825, IDE0300 // this is the implementation of Array.Empty<T>()
internal static readonly T[] Value = new T[0];
#pragma warning restore CA1825
#pragma warning restore CA1825, IDE0300
}

public static T[] Empty<T>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ namespace System

// Do not replace the array allocation with Array.Empty. We don't want to have the overhead of
// instantiating another generic type in addition to ArraySegment<T> for new type parameters.
#pragma warning disable CA1825
#pragma warning disable CA1825, IDE0300
public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]);
#pragma warning restore CA1825
#pragma warning restore CA1825, IDE0300

private readonly T[]? _array; // Do not rename (binary serialization)
private readonly int _offset; // Do not rename (binary serialization)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,7 @@ public static class BitConverter
/// </summary>
/// <param name="value">A Boolean value.</param>
/// <returns>A byte array with length 1.</returns>
public static byte[] GetBytes(bool value)
{
byte[] r = new byte[1];
r[0] = (value ? (byte)1 : (byte)0);
return r;
}
public static byte[] GetBytes(bool value) => [(value ? (byte)1 : (byte)0)];

/// <summary>
/// Converts a Boolean into a span of bytes.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ public class List<T> : IList<T>, IList, IReadOnlyList<T>
internal int _size; // Do not rename (binary serialization)
internal int _version; // Do not rename (binary serialization)

#pragma warning disable CA1825 // avoid the extra generic instantiation for Array.Empty<T>()
#pragma warning disable CA1825, IDE0300 // avoid the extra generic instantiation for Array.Empty<T>()
private static readonly T[] s_emptyArray = new T[0];
#pragma warning restore CA1825
#pragma warning restore CA1825, IDE0300

// Constructs a List. The list is initially empty and has a capacity
// of zero. Upon adding the first element to the list the capacity is
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2481,8 +2481,8 @@ public PowerOvfl(uint hi, uint mid, uint lo)
}
}

private static readonly PowerOvfl[] PowerOvflValues = new[]
{
private static readonly PowerOvfl[] PowerOvflValues =
[
// This is a table of the largest values that can be in the upper two
// uints of a 96-bit number that will not overflow when multiplied
// by a given power. For the upper word, this is a table of
Expand All @@ -2497,7 +2497,7 @@ public PowerOvfl(uint hi, uint mid, uint lo)
new PowerOvfl(4294, 4154504685, 2369172679), // 10^6 remainder 0.551616
new PowerOvfl(429, 2133437386, 4102387834), // 10^7 remainder 0.9551616
new PowerOvfl(42, 4078814305, 410238783), // 10^8 remainder 0.09991616
};
];

[StructLayout(LayoutKind.Explicit)]
private struct Buf12
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Private.CoreLib/src/System/Decimal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,7 @@ public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatPro
//
public static int[] GetBits(decimal d)
{
return new int[] { (int)d.Low, (int)d.Mid, (int)d.High, d._flags };
return [(int)d.Low, (int)d.Mid, (int)d.High, d._flags];
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public abstract partial class Delegate : ICloneable, ISerializable

protected virtual Delegate? RemoveImpl(Delegate d) => d.Equals(this) ? null : this;

public virtual Delegate[] GetInvocationList() => new Delegate[] { this };
public virtual Delegate[] GetInvocationList() => [this];

/// <summary>
/// Gets a value that indicates whether the <see cref="Delegate"/> has a single invocation target.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ sealed class MemberNotNullAttribute : Attribute
/// <param name="member">
/// The field or property member that is promised to be not-null.
/// </param>
public MemberNotNullAttribute(string member) => Members = new[] { member };
public MemberNotNullAttribute(string member) => Members = [member];

/// <summary>Initializes the attribute with the list of field and property members.</summary>
/// <param name="members">
Expand Down Expand Up @@ -171,7 +171,7 @@ sealed class MemberNotNullWhenAttribute : Attribute
public MemberNotNullWhenAttribute(bool returnValue, string member)
{
ReturnValue = returnValue;
Members = new[] { member };
Members = [member];
}

/// <summary>Initializes the attribute with the specified return value condition and list of field and property members.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo)
/// </summary>
public StackTrace(StackFrame frame)
{
_stackFrames = new StackFrame[] { frame };
_stackFrames = [frame];
_numOfFrames = 1;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,10 @@ private void CommitDispatchConfiguration()
}

// Enable the EventPipe session.
EventPipeProviderConfiguration[] providerConfiguration = new EventPipeProviderConfiguration[]
{
EventPipeProviderConfiguration[] providerConfiguration =
[
new EventPipeProviderConfiguration(NativeRuntimeEventSource.EventSourceName, (ulong)aggregatedKeywords, (uint)enableLevel, null)
};
];

ulong sessionID = EventPipeInternal.Enable(null, EventPipeSerializationFormat.NetTrace, DefaultEventListenerCircularMBSize, providerConfiguration);
if (sessionID == 0)
Expand Down
Loading

0 comments on commit 6068519

Please sign in to comment.