Skip to content

Commit

Permalink
Code style: use c# 12 collection literals (#810)
Browse files Browse the repository at this point in the history
  • Loading branch information
Romfos committed May 14, 2024
1 parent 4a5e6b6 commit 2cf5aad
Show file tree
Hide file tree
Showing 33 changed files with 113 additions and 115 deletions.
4 changes: 3 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_event = false:suggestion
csharp_style_namespace_declarations=file_scoped:warning
csharp_style_namespace_declarations = file_scoped:warning
dotnet_style_prefer_collection_expression = true:warning
dotnet_style_collection_initializer = true:warning

# ReSharper properties
resharper_int_align_switch_expressions = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ internal 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 All @@ -116,7 +116,7 @@ internal 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
2 changes: 1 addition & 1 deletion src/NSubstitute/Core/ArgumentSpecificationDequeue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace NSubstitute.Core;

public class ArgumentSpecificationDequeue : IArgumentSpecificationDequeue
{
private static readonly IArgumentSpecification[] EmptySpecifications = new IArgumentSpecification[0];
private static readonly IArgumentSpecification[] EmptySpecifications = [];

private readonly Func<IList<IArgumentSpecification>> _dequeueAllQueuedArgSpecs;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public bool IsSatisfiedBy(object? argument)

public string Format(object? argument, bool highlight)
{
var argArray = argument is IEnumerable enumerableArgs ? enumerableArgs.Cast<object>().ToArray() : new object[0];
var argArray = argument is IEnumerable enumerableArgs ? enumerableArgs.Cast<object>().ToArray() : [];
return Format(argArray, _argumentSpecifications).Join(", ");
}

Expand Down
2 changes: 1 addition & 1 deletion src/NSubstitute/Core/Call.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public void AssignSequenceNumber(long number)
object?[] originalArray = _originalArguments;
if (originalArray == _arguments && originalArray.Length > 0)
{
object?[] copy = originalArray.ToArray();
object?[] copy = [.. originalArray];
// If it happens that _originalArguments doesn't point to the `_arguments` anymore -
// it might happen that other thread already created a copy and mutated the original `_arguments` array.
// In this case it's unsafe to replace it with a copy.
Expand Down
2 changes: 1 addition & 1 deletion src/NSubstitute/Core/CustomHandlers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

public class CustomHandlers : ICustomHandlers
{
private readonly List<ICallHandler> _handlers = new();
private readonly List<ICallHandler> _handlers = [];
private readonly ISubstituteState _substituteState;

public IReadOnlyCollection<ICallHandler> Handlers => _handlers;
Expand Down
4 changes: 2 additions & 2 deletions src/NSubstitute/Core/DependencyInjection/NSubContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class NSubContainer : IConfigurableNSubContainer
{
private readonly NSubContainer? _parentContainer;
private readonly object _syncRoot;
private readonly Dictionary<Type, Registration> _registrations = new();
private readonly Dictionary<Type, Registration> _registrations = [];

public NSubContainer()
{
Expand Down Expand Up @@ -177,7 +177,7 @@ public object Resolve(Scope scope)

private class Scope : INSubResolver
{
private readonly Dictionary<Registration, object> _cache = new Dictionary<Registration, object>();
private readonly Dictionary<Registration, object> _cache = [];
private readonly NSubContainer _mostNestedContainer;

public Scope(NSubContainer mostNestedContainer)
Expand Down
2 changes: 1 addition & 1 deletion src/NSubstitute/Core/EventHandlerRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public class EventHandlerRegistry : IEventHandlerRegistry
// Events are not expected to be configured/raised concurrently, so simple locking should be sufficient.
// List lookup is O(n), but for really small size performance is comparable to dictionary.
// Given that normally a few events are configured only, it should be totally fine.
private readonly List<Tuple<string, List<object>>> _handlersForEvent = new();
private readonly List<Tuple<string, List<object>>> _handlersForEvent = [];

public void Add(string eventName, object handler)
{
Expand Down
2 changes: 1 addition & 1 deletion src/NSubstitute/Core/Events/DelegateEventWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ private bool LooksLikeAnEventStyleCall(ParameterInfo[] parameters)
sender = _providedArguments[0];
eventArgs = GetDefaultForEventArgType(eventArgsType);
}
return new[] { sender, eventArgs };
return [sender, eventArgs];
}

private static bool RequiredArgsHaveBeenProvided(object?[] providedArgs, ParameterInfo[] requiredArgs)
Expand Down
2 changes: 1 addition & 1 deletion src/NSubstitute/Core/Events/EventHandlerWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,6 @@ protected override object[] WorkOutRequiredArguments(ICall call)
{
var sender = _sender ?? call.Target();
var eventArgs = _eventArgs ?? GetDefaultForEventArgType(typeof(TEventArgs));
return new[] { sender, eventArgs };
return [sender, eventArgs];
}
}
2 changes: 1 addition & 1 deletion src/NSubstitute/Core/Events/RaiseEventWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ protected EventArgs GetDefaultForEventArgType(Type type)
, type.Name, RaiseMethodName);
throw new CannotCreateEventArgsException(message);
}
return (EventArgs)defaultConstructor.Invoke(new object[0]);
return (EventArgs)defaultConstructor.Invoke([]);
}

private static ConstructorInfo? GetDefaultConstructor(Type type) => type.GetConstructor(Type.EmptyTypes);
Expand Down
2 changes: 1 addition & 1 deletion src/NSubstitute/Core/Query.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

public class Query : IQuery, IQueryResults
{
private readonly List<CallSpecAndTarget> _querySpec = new();
private readonly List<CallSpecAndTarget> _querySpec = [];
private readonly HashSet<ICall> _matchingCalls = new(new CallSequenceNumberComparer());
private readonly ICallSpecificationFactory _callSpecificationFactory;

Expand Down
4 changes: 1 addition & 3 deletions src/NSubstitute/Core/ReflectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@ private static bool CanBePropertySetterCall(MethodInfo call)

private static PropertyInfo[] GetAllProperties(Type? type)
{
return type != null
? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
: new PropertyInfo[0];
return type?.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? [];
}
}
2 changes: 1 addition & 1 deletion src/NSubstitute/Core/ThreadLocalContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace NSubstitute.Core;

public class ThreadLocalContext : IThreadLocalContext
{
private static readonly IArgumentSpecification[] EmptySpecifications = new IArgumentSpecification[0];
private static readonly IArgumentSpecification[] EmptySpecifications = [];

private readonly RobustThreadLocal<ICallRouter?> _lastCallRouter;
private readonly RobustThreadLocal<IList<IArgumentSpecification>> _argumentSpecifications;
Expand Down
2 changes: 1 addition & 1 deletion src/NSubstitute/Extensions/ExceptionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ private static object FromException(object value, Exception exception)
{
var fromExceptionMethodInfo = typeof(Task).GetMethods(BindingFlags.Static | BindingFlags.Public).Single(m => m.Name == "FromException" && m.ContainsGenericParameters);
var specificFromExceptionMethod = fromExceptionMethodInfo.MakeGenericMethod(valueType.GenericTypeArguments);
return specificFromExceptionMethod.Invoke(null, new object[] { exception });
return specificFromExceptionMethod.Invoke(null, [exception]);
}

return Task.FromException(exception);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ private object GenerateTypeProxy(ICallRouter callRouter, Type typeToProxy, Type[
typeToProxy,
additionalInterfaces,
constructorArguments,
new IInterceptor[] { proxyIdInterceptor, forwardingInterceptor },
[proxyIdInterceptor, forwardingInterceptor],
proxyGenerationOptions);

forwardingInterceptor.SwitchToFullDispatchMode();
Expand All @@ -63,7 +63,7 @@ private object GenerateDelegateProxy(ICallRouter callRouter, Type delegateType,
typeToProxy: typeof(object),
additionalInterfaces: null,
constructorArguments: null,
interceptors: new IInterceptor[] { proxyIdInterceptor, forwardingInterceptor },
interceptors: [proxyIdInterceptor, forwardingInterceptor],
proxyGenerationOptions);

forwardingInterceptor.SwitchToFullDispatchMode();
Expand Down
2 changes: 1 addition & 1 deletion src/NSubstitute/Raise.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ private static object[] FixParamsArrayAmbiguity(object[] arguments, Type delegat

if (singleParameterType.IsInstanceOfType(arguments))
{
return new object[] { arguments };
return [arguments];
}

return arguments;
Expand Down
8 changes: 3 additions & 5 deletions src/NSubstitute/Routing/AutoValues/AutoObservableProvider.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System.Reflection;
using NSubstitute.Core;
using NSubstitute.Core;
using System.Reflection;

namespace NSubstitute.Routing.AutoValues;

Expand All @@ -23,9 +23,7 @@ public AutoObservableProvider(Lazy<IReadOnlyCollection<IAutoValueProvider>> auto
Type innerType = type.GetGenericArguments()[0];
var valueProvider = _autoValueProviders.Value.FirstOrDefault(vp => vp.CanProvideValueFor(innerType));
var value = valueProvider == null ? GetDefault(type) : valueProvider.GetValue(innerType);
return Activator.CreateInstance(
typeof(ReturnObservable<>).MakeGenericType(innerType)
, new object?[] { value });
return Activator.CreateInstance(typeof(ReturnObservable<>).MakeGenericType(innerType), [value]);
}

private static object? GetDefault(Type type)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public bool CanProvideValueFor(Type type)

public object GetValue(Type type)
{
return _substituteFactory.Create(new[] { type }, new object[0]);
return _substituteFactory.Create([type], []);
}

private bool IsPureVirtualClassWithParameterlessConstructor(Type type)
Expand Down
2 changes: 1 addition & 1 deletion src/NSubstitute/Routing/AutoValues/AutoTaskProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public object GetValue(Type type)
var value = valueProvider == null ? GetDefault(type) : valueProvider.GetValue(taskType);
var taskCompletionSourceType = typeof(TaskCompletionSource<>).MakeGenericType(taskType);
var taskCompletionSource = Activator.CreateInstance(taskCompletionSourceType);
taskCompletionSourceType.GetMethod(nameof(TaskCompletionSource<object>.SetResult))!.Invoke(taskCompletionSource, new[] { value });
taskCompletionSourceType.GetMethod(nameof(TaskCompletionSource<object>.SetResult))!.Invoke(taskCompletionSource, [value]);
return taskCompletionSourceType.GetProperty(nameof(TaskCompletionSource<object>.Task))!.GetValue(taskCompletionSource, null)!;
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ public IReadOnlyCollection<IAutoValueProvider> CreateProviders(ISubstituteFactor
() => result ?? throw new SubstituteInternalException("Value was not constructed yet."),
LazyThreadSafetyMode.PublicationOnly);

result = new IAutoValueProvider[]
{
result =
[
new AutoObservableProvider(lazyResult),
new AutoQueryableProvider(),
new AutoSubstituteProvider(substituteFactory),
new AutoStringProvider(),
new AutoArrayProvider(),
new AutoTaskProvider(lazyResult)
};
];

return result;
}
Expand Down
116 changes: 58 additions & 58 deletions src/NSubstitute/Routing/RouteFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,85 +30,85 @@ public class RouteFactory : IRouteFactory

public IRoute CallQuery(ISubstituteState state)
{
return new Route(new ICallHandler[] {
new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification)
, new AddCallToQueryResultHandler(_threadLocalContext)
, new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory)
, ReturnDefaultForReturnTypeHandler()
});
return new Route([
new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification),
new AddCallToQueryResultHandler(_threadLocalContext),
new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory),
ReturnDefaultForReturnTypeHandler()
]);
}
public IRoute CheckReceivedCalls(ISubstituteState state, MatchArgs matchArgs, Quantity requiredQuantity)
{
return new Route(new ICallHandler[] {
new ClearLastCallRouterHandler(_threadLocalContext)
, new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification)
, new CheckReceivedCallsHandler(state.ReceivedCalls, _callSpecificationFactory, _receivedCallsExceptionThrower, matchArgs, requiredQuantity)
, new ReturnAutoValue(AutoValueBehaviour.ReturnAndForgetValue, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory)
, ReturnDefaultForReturnTypeHandler()
});
return new Route([
new ClearLastCallRouterHandler(_threadLocalContext),
new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification),
new CheckReceivedCallsHandler(state.ReceivedCalls, _callSpecificationFactory, _receivedCallsExceptionThrower, matchArgs, requiredQuantity),
new ReturnAutoValue(AutoValueBehaviour.ReturnAndForgetValue, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory),
ReturnDefaultForReturnTypeHandler()
]);
}
public IRoute DoWhenCalled(ISubstituteState state, Action<CallInfo> doAction, MatchArgs matchArgs)
{
return new Route(new ICallHandler[] {
new ClearLastCallRouterHandler(_threadLocalContext)
, new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification)
, new SetActionForCallHandler(_callSpecificationFactory, state.CallActions, doAction, matchArgs)
, ReturnDefaultForReturnTypeHandler()
});
return new Route([
new ClearLastCallRouterHandler(_threadLocalContext),
new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification),
new SetActionForCallHandler(_callSpecificationFactory, state.CallActions, doAction, matchArgs),
ReturnDefaultForReturnTypeHandler()
]);
}
public IRoute DoNotCallBase(ISubstituteState state, MatchArgs matchArgs)
{
return new Route(new ICallHandler[] {
new ClearLastCallRouterHandler(_threadLocalContext)
, new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification)
, new DoNotCallBaseForCallHandler(_callSpecificationFactory, state.CallBaseConfiguration, matchArgs)
, ReturnDefaultForReturnTypeHandler()
});
return new Route([
new ClearLastCallRouterHandler(_threadLocalContext),
new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification),
new DoNotCallBaseForCallHandler(_callSpecificationFactory, state.CallBaseConfiguration, matchArgs),
ReturnDefaultForReturnTypeHandler()
]);
}
public IRoute CallBase(ISubstituteState state, MatchArgs matchArgs)
{
return new Route(new ICallHandler[] {
new ClearLastCallRouterHandler(_threadLocalContext)
, new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification)
, new CallBaseForCallHandler(_callSpecificationFactory, state.CallBaseConfiguration, matchArgs)
, ReturnDefaultForReturnTypeHandler()
});
return new Route([
new ClearLastCallRouterHandler(_threadLocalContext),
new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification),
new CallBaseForCallHandler(_callSpecificationFactory, state.CallBaseConfiguration, matchArgs),
ReturnDefaultForReturnTypeHandler()
]);
}
public IRoute RaiseEvent(ISubstituteState state, Func<ICall, object?[]> getEventArguments)
{
return new Route(new ICallHandler[] {
new ClearLastCallRouterHandler(_threadLocalContext)
, new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification)
, new RaiseEventHandler(state.EventHandlerRegistry, getEventArguments)
, ReturnDefaultForReturnTypeHandler()
});
return new Route([
new ClearLastCallRouterHandler(_threadLocalContext),
new ClearUnusedCallSpecHandler(_threadLocalContext.PendingSpecification),
new RaiseEventHandler(state.EventHandlerRegistry, getEventArguments),
ReturnDefaultForReturnTypeHandler()
]);
}
public IRoute RecordCallSpecification(ISubstituteState state)
{
return new Route(new ICallHandler[] {
new RecordCallSpecificationHandler(_threadLocalContext.PendingSpecification, _callSpecificationFactory, state.CallActions)
, new PropertySetterHandler(_propertyHelper, state.ConfigureCall)
, new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory)
, new ReturnFromAndConfigureDynamicCall(state.ConfigureCall)
, ReturnDefaultForReturnTypeHandler()
});
return new Route([
new RecordCallSpecificationHandler(_threadLocalContext.PendingSpecification, _callSpecificationFactory, state.CallActions),
new PropertySetterHandler(_propertyHelper, state.ConfigureCall),
new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory),
new ReturnFromAndConfigureDynamicCall(state.ConfigureCall),
ReturnDefaultForReturnTypeHandler()
]);
}
public IRoute RecordReplay(ISubstituteState state)
{
return new Route(new ICallHandler[] {
new TrackLastCallHandler(_threadLocalContext.PendingSpecification)
, new RecordCallHandler(state.ReceivedCalls, _sequenceNumberGenerator)
, new EventSubscriptionHandler(state.EventHandlerRegistry)
, new PropertySetterHandler(_propertyHelper, state.ConfigureCall)
, new DoActionsCallHandler(state.CallActions)
, new ReturnConfiguredResultHandler(state.CallResults)
, new ReturnResultForTypeHandler(state.ResultsForType)
, new ReturnFromBaseIfRequired(state.CallBaseConfiguration)
, new ReturnFromCustomHandlers(state.CustomHandlers)
, new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory)
, new ReturnFromAndConfigureDynamicCall(state.ConfigureCall)
, ReturnDefaultForReturnTypeHandler()
});
return new Route([
new TrackLastCallHandler(_threadLocalContext.PendingSpecification),
new RecordCallHandler(state.ReceivedCalls, _sequenceNumberGenerator),
new EventSubscriptionHandler(state.EventHandlerRegistry),
new PropertySetterHandler(_propertyHelper, state.ConfigureCall),
new DoActionsCallHandler(state.CallActions),
new ReturnConfiguredResultHandler(state.CallResults),
new ReturnResultForTypeHandler(state.ResultsForType),
new ReturnFromBaseIfRequired(state.CallBaseConfiguration),
new ReturnFromCustomHandlers(state.CustomHandlers),
new ReturnAutoValue(AutoValueBehaviour.UseValueForSubsequentCalls, state.AutoValueProviders, state.AutoValuesCallResults, _callSpecificationFactory),
new ReturnFromAndConfigureDynamicCall(state.ConfigureCall),
ReturnDefaultForReturnTypeHandler()
]);
}

private ReturnDefaultForReturnTypeHandler ReturnDefaultForReturnTypeHandler() => new(_defaultForType);
Expand Down

0 comments on commit 2cf5aad

Please sign in to comment.