diff --git a/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/AlternativeMonad/MatchToOrElseCodeFix.cs b/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/AlternativeMonad/MatchToOrElseCodeFix.cs index 588e3e5b..96cf5761 100644 --- a/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/AlternativeMonad/MatchToOrElseCodeFix.cs +++ b/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/AlternativeMonad/MatchToOrElseCodeFix.cs @@ -43,42 +43,27 @@ private static IdentifierNameSyntax DiagnosticIdToMethodName(string diagnosticId _ => throw new NotSupportedException("Internal error: This branch should be unreachable"), }; - private sealed class GetOrElseCodeFixAction : CodeAction + private sealed class GetOrElseCodeFixAction( + Document document, + InvocationExpressionSyntax invocationExpression, + MemberAccessExpressionSyntax memberAccessExpression, + int errorStateArgumentIndex, + IdentifierNameSyntax methodName) : CodeAction { - private readonly Document _document; - private readonly InvocationExpressionSyntax _invocationExpression; - private readonly MemberAccessExpressionSyntax _memberAccessExpression; - private readonly int _errorStateArgumentIndex; - private readonly IdentifierNameSyntax _methodName; - - public GetOrElseCodeFixAction( - Document document, - InvocationExpressionSyntax invocationExpression, - MemberAccessExpressionSyntax memberAccessExpression, - int errorStateArgumentIndex, - IdentifierNameSyntax methodName) - { - _document = document; - _invocationExpression = invocationExpression; - _memberAccessExpression = memberAccessExpression; - _errorStateArgumentIndex = errorStateArgumentIndex; - _methodName = methodName; - } - - public override string Title => $"Replace {MatchMethodName} with {_methodName.Identifier}"; + public override string Title => $"Replace {MatchMethodName} with {methodName.Identifier}"; public override string? EquivalenceKey => nameof(MatchToOrElseCodeFix); protected override async Task GetChangedDocumentAsync(CancellationToken cancellationToken) { - var editor = await DocumentEditor.CreateAsync(_document, cancellationToken).ConfigureAwait(false); + var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); editor.ReplaceNode( - _invocationExpression, - _invocationExpression.WithExpression(_memberAccessExpression - .WithName(_methodName)) + invocationExpression, + invocationExpression.WithExpression(memberAccessExpression + .WithName(methodName)) .WithArgumentList(ArgumentList(SingletonSeparatedList( - Argument(_invocationExpression.ArgumentList.Arguments[_errorStateArgumentIndex].Expression))))); + Argument(invocationExpression.ArgumentList.Arguments[errorStateArgumentIndex].Expression))))); return editor.GetChangedDocument(); } diff --git a/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/EnumerableRepeatNeverCodeFix.cs b/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/EnumerableRepeatNeverCodeFix.cs index beba969d..3e1cd7c5 100644 --- a/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/EnumerableRepeatNeverCodeFix.cs +++ b/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/EnumerableRepeatNeverCodeFix.cs @@ -40,28 +40,20 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) private static Diagnostic GetDiagnostic(CodeFixContext context) => context.Diagnostics.First(); - private sealed class ToEnumerableEmptyCodeAction : CodeAction + private sealed class ToEnumerableEmptyCodeAction( + Document document, + InvocationExpressionSyntax invocationExpression, + int valueParameterIndex) : CodeAction { - private readonly Document _document; - private readonly InvocationExpressionSyntax _invocationExpression; - private readonly int _valueParameterIndex; - - public ToEnumerableEmptyCodeAction(Document document, InvocationExpressionSyntax invocationExpression, int valueParameterIndex) - { - _document = document; - _invocationExpression = invocationExpression; - _valueParameterIndex = valueParameterIndex; - } - public override string Title => EnumerableRepeatNeverCodeFixTitle; public override string EquivalenceKey => nameof(ToEnumerableEmptyCodeAction); protected override async Task GetChangedDocumentAsync(CancellationToken cancellationToken) { - var editor = await DocumentEditor.CreateAsync(_document, cancellationToken).ConfigureAwait(false); - var valueParameter = _invocationExpression.ArgumentList.Arguments[_valueParameterIndex]; - editor.ReplaceNode(_invocationExpression, CreateEnumerableReturnRoot(valueParameter, editor.SemanticModel, editor.Generator)); + var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + var valueParameter = invocationExpression.ArgumentList.Arguments[valueParameterIndex]; + editor.ReplaceNode(invocationExpression, CreateEnumerableReturnRoot(valueParameter, editor.SemanticModel, editor.Generator)); return editor.GetChangedDocument(); } diff --git a/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/ReplaceParameterReferenceRewriter.cs b/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/ReplaceParameterReferenceRewriter.cs index af6815d0..1ec6329b 100644 --- a/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/ReplaceParameterReferenceRewriter.cs +++ b/Funcky.Analyzers/Funcky.Analyzers.CodeFixes/ReplaceParameterReferenceRewriter.cs @@ -5,25 +5,17 @@ namespace Funcky.Analyzers; -internal sealed class ReplaceParameterReferenceRewriter : CSharpSyntaxRewriter +internal sealed class ReplaceParameterReferenceRewriter( + SemanticModel semanticModel, + string parameterName, + ExpressionSyntax replacement) + : CSharpSyntaxRewriter(visitIntoStructuredTrivia: false) { - private readonly SemanticModel _semanticModel; - private readonly string _parameterName; - private readonly ExpressionSyntax _replacement; - - public ReplaceParameterReferenceRewriter(SemanticModel semanticModel, string parameterName, ExpressionSyntax replacement) - : base(visitIntoStructuredTrivia: false) - { - _semanticModel = semanticModel; - _parameterName = parameterName; - _replacement = replacement; - } - public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) { - if (_semanticModel.GetOperation(node) is IParameterReferenceOperation { Parameter.Name: var name } && name == _parameterName) + if (semanticModel.GetOperation(node) is IParameterReferenceOperation { Parameter.Name: var name } && name == parameterName) { - return _replacement.WithTriviaFrom(node); + return replacement.WithTriviaFrom(node); } return node; diff --git a/Funcky.Async.Test/TestUtilities/OptionProducer.cs b/Funcky.Async.Test/TestUtilities/OptionProducer.cs index 6527c7a1..837f8682 100644 --- a/Funcky.Async.Test/TestUtilities/OptionProducer.cs +++ b/Funcky.Async.Test/TestUtilities/OptionProducer.cs @@ -1,23 +1,14 @@ namespace Funcky.Async.Test.TestUtilities; -internal sealed class OptionProducer +internal sealed class OptionProducer(int retriesNeeded, T result) where T : notnull { - private readonly T _result; - private readonly int _retriesNeeded; - - public OptionProducer(int retriesNeeded, T result) - { - _retriesNeeded = retriesNeeded; - _result = result; - } - public int Called { get; private set; } public ValueTask> ProduceAsync() { Called += 1; - return ValueTask.FromResult(Option.FromBoolean(_retriesNeeded == (Called - 1), _result)); + return ValueTask.FromResult(Option.FromBoolean(retriesNeeded == (Called - 1), result)); } } diff --git a/Funcky.Async/AsyncSequence/AsyncSequence.CycleRange.cs b/Funcky.Async/AsyncSequence/AsyncSequence.CycleRange.cs index d0b75213..882509db 100644 --- a/Funcky.Async/AsyncSequence/AsyncSequence.CycleRange.cs +++ b/Funcky.Async/AsyncSequence/AsyncSequence.CycleRange.cs @@ -18,17 +18,13 @@ public static AsyncCycleBuffer Create(IAsyncEnumerable new(source, maxCycles); } - private sealed class AsyncCycleBuffer : IAsyncBuffer + private sealed class AsyncCycleBuffer(IAsyncEnumerable source, Option maxCycles = default) : IAsyncBuffer { private readonly List _buffer = new(); - private readonly IAsyncEnumerator _source; - private readonly Option _maxCycles; + private readonly IAsyncEnumerator _source = source.GetAsyncEnumerator(); private bool _disposed; - public AsyncCycleBuffer(IAsyncEnumerable source, Option maxCycles = default) - => (_source, _maxCycles) = (source.GetAsyncEnumerator(), maxCycles); - public async ValueTask DisposeAsync() { if (!_disposed) @@ -74,7 +70,7 @@ private async IAsyncEnumerator GetEnumeratorInternal() if (_buffer.Count is 0) { - if (_maxCycles.Match(none: true, some: False)) + if (maxCycles.Match(none: true, some: False)) { throw new InvalidOperationException("you cannot cycle an empty enumerable"); } @@ -99,10 +95,10 @@ private async IAsyncEnumerator GetEnumeratorInternal() } private bool HasNoCycles() - => _maxCycles.Match(none: false, some: maxCycles => maxCycles is 0); + => maxCycles.Match(none: false, some: maxCycles => maxCycles is 0); private bool IsCycling(int cycle) - => _maxCycles.Match( + => maxCycles.Match( none: true, some: maxCycles => cycle < maxCycles); diff --git a/Funcky.Async/Extensions/AsyncEnumerableExtensions/Memoize.cs b/Funcky.Async/Extensions/AsyncEnumerableExtensions/Memoize.cs index 71fac176..61478d5c 100644 --- a/Funcky.Async/Extensions/AsyncEnumerableExtensions/Memoize.cs +++ b/Funcky.Async/Extensions/AsyncEnumerableExtensions/Memoize.cs @@ -24,17 +24,14 @@ public static MemoizedAsyncBuffer Create(IAsyncEnumerable new(source); } - private sealed class BorrowedAsyncBuffer : IAsyncBuffer + private sealed class BorrowedAsyncBuffer(IAsyncBuffer inner) : IAsyncBuffer { - private readonly IAsyncBuffer _inner; private bool _disposed; - public BorrowedAsyncBuffer(IAsyncBuffer inner) => _inner = inner; - public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) { ThrowIfDisposed(); - return _inner.GetAsyncEnumerator(cancellationToken); + return inner.GetAsyncEnumerator(cancellationToken); } public ValueTask DisposeAsync() @@ -52,16 +49,13 @@ private void ThrowIfDisposed() } } - private sealed class MemoizedAsyncBuffer : IAsyncBuffer + private sealed class MemoizedAsyncBuffer(IAsyncEnumerable source) : IAsyncBuffer { private readonly List _buffer = new(); - private readonly IAsyncEnumerator _source; + private readonly IAsyncEnumerator _source = source.GetAsyncEnumerator(); private bool _disposed; - public MemoizedAsyncBuffer(IAsyncEnumerable source) - => _source = source.GetAsyncEnumerator(); - public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) { ThrowIfDisposed(); diff --git a/Funcky.Async/Extensions/AsyncEnumerableExtensions/Sequence.cs b/Funcky.Async/Extensions/AsyncEnumerableExtensions/Sequence.cs index bf8c540c..5487ebc5 100644 --- a/Funcky.Async/Extensions/AsyncEnumerableExtensions/Sequence.cs +++ b/Funcky.Async/Extensions/AsyncEnumerableExtensions/Sequence.cs @@ -59,13 +59,10 @@ private static async ValueTask>> Trave return UnsafeEither>.Right(builder.ToImmutable()); } - private sealed class SequenceLazyInternal<[DynamicallyAccessedMembers(PublicParameterlessConstructor)] TSource> + private sealed class SequenceLazyInternal<[DynamicallyAccessedMembers(PublicParameterlessConstructor)] TSource>( + IAsyncEnumerable> source) { - private readonly IAsyncEnumerable> _source; - - public SequenceLazyInternal(IAsyncEnumerable> source) => _source = source; - // Workaround for https://github.com/dotnet/linker/issues/1416 - public IAsyncEnumerable Invoke() => _source.Select(lazy => lazy.Value); + public IAsyncEnumerable Invoke() => source.Select(lazy => lazy.Value); } } diff --git a/Funcky.Test.Internal/Data/Person.cs b/Funcky.Test.Internal/Data/Person.cs index fc295c86..d5145383 100644 --- a/Funcky.Test.Internal/Data/Person.cs +++ b/Funcky.Test.Internal/Data/Person.cs @@ -1,11 +1,8 @@ namespace Funcky.Test.Internal.Data; -public sealed class Person : IComparable, IEquatable +public sealed class Person(int age) : IComparable, IEquatable { - public Person(int age) - => Age = age; - - public int Age { get; } + public int Age { get; } = age; public int CompareTo(Person? other) => other != null diff --git a/Funcky.Test/Extensions/EnumerableExtensions/FailOnEnumerationList.cs b/Funcky.Test/Extensions/EnumerableExtensions/FailOnEnumerationList.cs index 528b3a6c..cf4d5300 100644 --- a/Funcky.Test/Extensions/EnumerableExtensions/FailOnEnumerationList.cs +++ b/Funcky.Test/Extensions/EnumerableExtensions/FailOnEnumerationList.cs @@ -2,22 +2,17 @@ namespace Funcky.Test.Extensions.EnumerableExtensions; -internal sealed class FailOnEnumerationList : IList +internal sealed class FailOnEnumerationList(int length) : IList { - private readonly int _length; - - public FailOnEnumerationList(int length) - => _length = length; - public int Count - => _length; + => length; public bool IsReadOnly => true; public int this[int index] { - get => index >= 0 && index < _length ? index : throw new IndexOutOfRangeException(); + get => index >= 0 && index < length ? index : throw new IndexOutOfRangeException(); set => throw new NotSupportedException(); } diff --git a/Funcky.Test/Extensions/SideEffect.cs b/Funcky.Test/Extensions/SideEffect.cs index 8b45d5b4..7c5c5b78 100644 --- a/Funcky.Test/Extensions/SideEffect.cs +++ b/Funcky.Test/Extensions/SideEffect.cs @@ -2,10 +2,7 @@ namespace Funcky.Test.Extensions; internal sealed class SideEffect { - private string _string; - - public SideEffect() - => _string = string.Empty; + private string _string = string.Empty; public void Store(string s) => _string = s; diff --git a/Funcky.Test/Extensions/StringExtensions/IndexOfTest.cs b/Funcky.Test/Extensions/StringExtensions/IndexOfTest.cs index 4749e09b..1aa64436 100644 --- a/Funcky.Test/Extensions/StringExtensions/IndexOfTest.cs +++ b/Funcky.Test/Extensions/StringExtensions/IndexOfTest.cs @@ -3,7 +3,7 @@ namespace Funcky.Test.Extensions.StringExtensions; -public sealed class IndexOfTest +public sealed class IndexOfTest(ITestOutputHelper testOutputHelper) { private const int NumberOfThisParametersInExtensionMethods = 1; @@ -14,13 +14,6 @@ public sealed class IndexOfTest private const char ExistingNeedleChar = 'y'; private const int NeedlePosition = 2; - private readonly ITestOutputHelper _testOutputHelper; - - public IndexOfTest(ITestOutputHelper testOutputHelper) - { - _testOutputHelper = testOutputHelper; - } - [Theory] [MemberData(nameof(InvalidIndexes))] public void ReturnsNoneIfNeedleIsNotFound(Option index) @@ -117,7 +110,7 @@ public void AllOverloadsOfIndexOfAreSupported() private static IEnumerable GetIndexOfMethods() => typeof(string).GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(IsIndexOfMethod); - private void WriteToTestOutput(object value) => _testOutputHelper.WriteLine(value.ToString()); + private void WriteToTestOutput(object value) => testOutputHelper.WriteLine(value.ToString()); private static Option GetMatchingExtensionMethod(MethodInfo originalMethod) { diff --git a/Funcky.Test/Monads/OptionEqualityComparerTest.cs b/Funcky.Test/Monads/OptionEqualityComparerTest.cs index 8bae5315..b8299d31 100644 --- a/Funcky.Test/Monads/OptionEqualityComparerTest.cs +++ b/Funcky.Test/Monads/OptionEqualityComparerTest.cs @@ -52,13 +52,9 @@ private sealed class ThrowingEqualityComparer : EqualityComparer public override int GetHashCode(T obj) => throw new NotSupportedException(); } - private sealed class ConstantEqualityComparer : EqualityComparer + private sealed class ConstantEqualityComparer(bool areEqual) : EqualityComparer { - private readonly bool _areEqual; - - public ConstantEqualityComparer(bool areEqual) => _areEqual = areEqual; - - public override bool Equals(T? x, T? y) => _areEqual; + public override bool Equals(T? x, T? y) => areEqual; public override int GetHashCode(T obj) => throw new NotSupportedException(); } diff --git a/Funcky.Test/TestUtils/OptionProducer.cs b/Funcky.Test/TestUtils/OptionProducer.cs index 48f1b5d0..501f0bad 100644 --- a/Funcky.Test/TestUtils/OptionProducer.cs +++ b/Funcky.Test/TestUtils/OptionProducer.cs @@ -1,23 +1,14 @@ namespace Funcky.Test.TestUtils; -internal sealed class OptionProducer +internal sealed class OptionProducer(int retriesNeeded, T result) where T : notnull { - private readonly T _result; - private readonly int _retriesNeeded; - - public OptionProducer(int retriesNeeded, T result) - { - _retriesNeeded = retriesNeeded; - _result = result; - } - public int Called { get; private set; } public Option Produce() { Called += 1; - return Option.FromBoolean(_retriesNeeded == (Called - 1), _result); + return Option.FromBoolean(retriesNeeded == (Called - 1), result); } } diff --git a/Funcky.Test/TestUtils/QueryableExtensions.cs b/Funcky.Test/TestUtils/QueryableExtensions.cs index 271902a2..45e67633 100644 --- a/Funcky.Test/TestUtils/QueryableExtensions.cs +++ b/Funcky.Test/TestUtils/QueryableExtensions.cs @@ -8,37 +8,29 @@ internal static class QueryableExtensions public static IQueryable PreventAccidentalUseAsEnumerable(this IQueryable source) => new QueryableDisallowingUseAsEnumerable(source); - private sealed class QueryableDisallowingUseAsEnumerable : IQueryable + private sealed class QueryableDisallowingUseAsEnumerable(IQueryable queryable) : IQueryable { - private readonly IQueryable _queryable; + public Type ElementType => queryable.ElementType; - public QueryableDisallowingUseAsEnumerable(IQueryable queryable) => _queryable = queryable; + public Expression Expression => queryable.Expression; - public Type ElementType => _queryable.ElementType; - - public Expression Expression => _queryable.Expression; - - public IQueryProvider Provider => new QueryProvider(_queryable.Provider); + public IQueryProvider Provider => new QueryProvider(queryable.Provider); public IEnumerator GetEnumerator() => throw new InvalidOperationException("Queryable should not be used as Enumerable"); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - private sealed class QueryProvider : IQueryProvider + private sealed class QueryProvider(IQueryProvider provider) : IQueryProvider { - private readonly IQueryProvider _provider; - - public QueryProvider(IQueryProvider provider) => _provider = provider; - public IQueryable CreateQuery(Expression expression) => throw new NotImplementedException(); public IQueryable CreateQuery(Expression expression) - => new QueryableDisallowingUseAsEnumerable(_provider.CreateQuery(expression)); + => new QueryableDisallowingUseAsEnumerable(provider.CreateQuery(expression)); public object? Execute(Expression expression) => throw new NotImplementedException(); public TResult Execute(Expression expression) - => _provider.Execute(expression); + => provider.Execute(expression); } } } diff --git a/Funcky.Test/TestUtils/RepeatingSequence.cs b/Funcky.Test/TestUtils/RepeatingSequence.cs index 62d77033..608f4193 100644 --- a/Funcky.Test/TestUtils/RepeatingSequence.cs +++ b/Funcky.Test/TestUtils/RepeatingSequence.cs @@ -7,26 +7,17 @@ public static class RepeatingSequence public static RepeatingSequenceHelper IsSequenceRepeating(this IEnumerable sequence, IEnumerable pattern) => new(sequence, pattern); - public class RepeatingSequenceHelper + public class RepeatingSequenceHelper(IEnumerable sequence, IEnumerable pattern) { - private readonly IEnumerable _sequence; - private readonly IEnumerable _pattern; - - internal RepeatingSequenceHelper(IEnumerable sequence, IEnumerable pattern) - { - _sequence = sequence; - _pattern = pattern; - } - public bool NTimes(int count) => Enumerable .Range(0, count) .Aggregate(true, AggregateEquality); public bool AggregateEquality(bool b, int i) - => b && _sequence - .Skip(i * _pattern.Count()) - .Zip(_pattern, (l, r) => l == r) + => b && sequence + .Skip(i * pattern.Count()) + .Zip(pattern, (l, r) => l == r) .All(Identity); } } diff --git a/Funcky/Extensions/EnumerableExtensions/Grouping.cs b/Funcky/Extensions/EnumerableExtensions/Grouping.cs index 51f2b7f7..3342e113 100644 --- a/Funcky/Extensions/EnumerableExtensions/Grouping.cs +++ b/Funcky/Extensions/EnumerableExtensions/Grouping.cs @@ -5,25 +5,17 @@ namespace Funcky.Extensions; public static partial class EnumerableExtensions { - internal class Grouping : IGrouping, IReadOnlyList, IList + internal class Grouping(TKey key, IImmutableList elements) : IGrouping, IReadOnlyList, IList { - private readonly IImmutableList _elements; + public TKey Key => key; - internal Grouping(TKey key, IImmutableList elements) - { - Key = key; - _elements = elements; - } - - public TKey Key { get; } - - public int Count => _elements.Count; + public int Count => elements.Count; public bool IsReadOnly => true; public TElement this[int index] { - get => _elements[index]; + get => elements[index]; set => throw new NotSupportedException(); } @@ -34,16 +26,16 @@ public void Clear() => throw new NotSupportedException(); public bool Contains(TElement element) - => _elements.Contains(element); + => elements.Contains(element); public void CopyTo(TElement[] array, int arrayIndex) => throw new NotSupportedException(); public IEnumerator GetEnumerator() - => _elements.GetEnumerator(); + => elements.GetEnumerator(); public int IndexOf(TElement element) - => _elements.IndexOf(element); + => elements.IndexOf(element); public void Insert(int index, TElement element) => throw new NotSupportedException(); diff --git a/Funcky/Extensions/EnumerableExtensions/Materialize.cs b/Funcky/Extensions/EnumerableExtensions/Materialize.cs index c2550380..ee4d5cdb 100644 --- a/Funcky/Extensions/EnumerableExtensions/Materialize.cs +++ b/Funcky/Extensions/EnumerableExtensions/Materialize.cs @@ -38,48 +38,40 @@ public static IReadOnlyCollection Materialize DefaultMaterializer(IEnumerable source) => source.ToImmutableList(); - private class CollectionAsReadOnlyCollectionProxy : ICollection, IReadOnlyCollection + private class CollectionAsReadOnlyCollectionProxy(ICollection collection) : ICollection, IReadOnlyCollection { - private readonly ICollection _collection; + public int Count => collection.Count; - public CollectionAsReadOnlyCollectionProxy(ICollection collection) => _collection = collection; + public bool IsReadOnly => collection.IsReadOnly; - public int Count => _collection.Count; - - public bool IsReadOnly => _collection.IsReadOnly; - - public IEnumerator GetEnumerator() => _collection.GetEnumerator(); + public IEnumerator GetEnumerator() => collection.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public void Add(T item) => _collection.Add(item); + public void Add(T item) => collection.Add(item); - public void Clear() => _collection.Clear(); + public void Clear() => collection.Clear(); - public bool Contains(T item) => _collection.Contains(item); + public bool Contains(T item) => collection.Contains(item); - public void CopyTo(T[] array, int arrayIndex) => _collection.CopyTo(array, arrayIndex); + public void CopyTo(T[] array, int arrayIndex) => collection.CopyTo(array, arrayIndex); - public bool Remove(T item) => _collection.Remove(item); + public bool Remove(T item) => collection.Remove(item); } - private sealed class ListAsReadOnlyCollectionProxy : CollectionAsReadOnlyCollectionProxy, IList, IReadOnlyList + private sealed class ListAsReadOnlyCollectionProxy(IList list) + : CollectionAsReadOnlyCollectionProxy(list), IList, IReadOnlyList { - private readonly IList _list; - - public ListAsReadOnlyCollectionProxy(IList list) - : base(list) => _list = list; - public T this[int index] { - get => _list[index]; - set => _list[index] = value; + get => list[index]; + set => list[index] = value; } - public int IndexOf(T item) => _list.IndexOf(item); + public int IndexOf(T item) => list.IndexOf(item); - public void Insert(int index, T item) => _list.Insert(index, item); + public void Insert(int index, T item) => list.Insert(index, item); - public void RemoveAt(int index) => _list.RemoveAt(index); + public void RemoveAt(int index) => list.RemoveAt(index); } } diff --git a/Funcky/Extensions/EnumerableExtensions/Memoize.cs b/Funcky/Extensions/EnumerableExtensions/Memoize.cs index 0d585cdb..d98335a6 100644 --- a/Funcky/Extensions/EnumerableExtensions/Memoize.cs +++ b/Funcky/Extensions/EnumerableExtensions/Memoize.cs @@ -28,17 +28,14 @@ public static MemoizedBuffer Create(IEnumerable sourc => new(source); } - private sealed class BorrowedBuffer : IBuffer + private sealed class BorrowedBuffer(IBuffer inner) : IBuffer { - private readonly IBuffer _inner; private bool _disposed; - public BorrowedBuffer(IBuffer inner) => _inner = inner; - public IEnumerator GetEnumerator() { ThrowIfDisposed(); - return _inner.GetEnumerator(); + return inner.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); @@ -54,16 +51,13 @@ private void ThrowIfDisposed() } } - private sealed class MemoizedBuffer : IBuffer + private sealed class MemoizedBuffer(IEnumerable source) : IBuffer { private readonly List _buffer = new(); - private readonly IEnumerator _source; + private readonly IEnumerator _source = source.GetEnumerator(); private bool _disposed; - public MemoizedBuffer(IEnumerable source) - => _source = source.GetEnumerator(); - public IEnumerator GetEnumerator() { ThrowIfDisposed(); diff --git a/Funcky/Extensions/EnumerableExtensions/Sequence.cs b/Funcky/Extensions/EnumerableExtensions/Sequence.cs index 138309c6..dc2c4b71 100644 --- a/Funcky/Extensions/EnumerableExtensions/Sequence.cs +++ b/Funcky/Extensions/EnumerableExtensions/Sequence.cs @@ -57,10 +57,9 @@ private static UnsafeEither> Traverse + (IEnumerable> source) { - private readonly IEnumerable> _source; - - public SequenceLazy(IEnumerable> source) => _source = source; + private readonly IEnumerable> _source = source; public IEnumerable Invoke() => _source.Select(static lazy => lazy.Value); } diff --git a/Funcky/Internal/ListWithSelector.cs b/Funcky/Internal/ListWithSelector.cs index 6eff9879..e63fea87 100644 --- a/Funcky/Internal/ListWithSelector.cs +++ b/Funcky/Internal/ListWithSelector.cs @@ -8,23 +8,19 @@ public static ListWithSelector Create(IList< => new(source, selector); } -internal class ListWithSelector : IList +internal class ListWithSelector(IList source, Func, Func> selector) : IList { - private readonly IList _source; - private readonly Func _selector; - - public ListWithSelector(IList source, Func, Func> selector) - => (_source, _selector) = (source, selector(source)); + private readonly Func _selector = selector(source); public int Count - => _source.Count; + => source.Count; public bool IsReadOnly => true; public TResult this[int index] { - get => _selector(_source[index], index); + get => _selector(source[index], index); set => throw new NotSupportedException(); } @@ -35,19 +31,19 @@ public void Clear() => throw new NotSupportedException(); public bool Contains(TResult item) - => _source.Select(_selector).Contains(item); + => source.Select(_selector).Contains(item); public void CopyTo(TResult[] array, int arrayIndex) { var index = arrayIndex; - foreach (var element in _source.Skip(arrayIndex).Select(_selector)) + foreach (var element in source.Skip(arrayIndex).Select(_selector)) { array[index++] = element; } } public IEnumerator GetEnumerator() - => _source + => source .Select(_selector) .GetEnumerator(); diff --git a/Funcky/Internal/RangeEnumerable.cs b/Funcky/Internal/RangeEnumerable.cs index 5e9ed258..586ab89b 100644 --- a/Funcky/Internal/RangeEnumerable.cs +++ b/Funcky/Internal/RangeEnumerable.cs @@ -3,15 +3,10 @@ namespace Funcky.Internal; -internal class RangeEnumerable : IEnumerable +internal class RangeEnumerable(Range range) : IEnumerable { - private readonly Range _range; - - public RangeEnumerable(Range range) - => _range = range; - public IEnumerator GetEnumerator() - => _range.GetEnumerator(); + => range.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); diff --git a/Funcky/Internal/SlidingWindowQueue.cs b/Funcky/Internal/SlidingWindowQueue.cs index d7a27d46..fa041a9c 100644 --- a/Funcky/Internal/SlidingWindowQueue.cs +++ b/Funcky/Internal/SlidingWindowQueue.cs @@ -2,20 +2,16 @@ namespace Funcky.Internal; -internal sealed class SlidingWindowQueue +internal sealed class SlidingWindowQueue(int width) { - private readonly int _width; private int _currentWidth; private ImmutableQueue _window = ImmutableQueue.Empty; - public SlidingWindowQueue(int width) - => _width = width; - public IReadOnlyList Window => _window.ToImmutableList(); public bool IsFull - => _width == _currentWidth; + => width == _currentWidth; public SlidingWindowQueue Enqueue(TSource element) { @@ -39,7 +35,7 @@ private void DequeueWithWidth() private void KeepWindowWidth() { - if (_currentWidth > _width) + if (_currentWidth > width) { DequeueWithWidth(); } diff --git a/Funcky/Monads/Either/Either.Debugger.cs b/Funcky/Monads/Either/Either.Debugger.cs index fb2ab5e7..7b32f769 100644 --- a/Funcky/Monads/Either/Either.Debugger.cs +++ b/Funcky/Monads/Either/Either.Debugger.cs @@ -14,16 +14,12 @@ public readonly partial struct Either right: static _ => "Right"); } -internal sealed class EitherDebugView +internal sealed class EitherDebugView(Either either) where TLeft : notnull where TRight : notnull { - private readonly Either _either; - - public EitherDebugView(Either either) => _either = either; - [DebuggerBrowsable(RootHidden)] - public object Value => _either.Match( + public object Value => either.Match( uninitialized: static () => new { }, left: left => new { Value = left }, right: right => new { Value = right }); diff --git a/Funcky/Monads/Lazy/Lazy.Monad.cs b/Funcky/Monads/Lazy/Lazy.Monad.cs index 3fb554ce..28a1c8b1 100644 --- a/Funcky/Monads/Lazy/Lazy.Monad.cs +++ b/Funcky/Monads/Lazy/Lazy.Monad.cs @@ -20,30 +20,21 @@ public static partial class LazyExtensions // This class is needed because the implicitly generated class that would be generated for a lambda // wouldn't have generic types annotated with DynamicallyAccessedMembers, which would result in a warning. private sealed class LazySelect<[DynamicallyAccessedMembers(PublicParameterlessConstructor)] T, [DynamicallyAccessedMembers(PublicParameterlessConstructor)] TResult> + (Lazy source, Func selector) { - private readonly Lazy _lazy; - private readonly Func _selector; - - public LazySelect(Lazy source, Func selector) => (_lazy, _selector) = (source, selector); - - public TResult Apply() => _selector(_lazy.Value); + public TResult Apply() => selector(source.Value); } // This class is needed because the implicitly generated class that would be generated for a lambda // wouldn't have generic types annotated with DynamicallyAccessedMembers, which would result in a warning. private sealed class LazySelectMany<[DynamicallyAccessedMembers(PublicParameterlessConstructor)] T, [DynamicallyAccessedMembers(PublicParameterlessConstructor)] TA, [DynamicallyAccessedMembers(PublicParameterlessConstructor)] TResult> + (Lazy lazy, Func> selector, Func resultSelector) { - private readonly Lazy _lazy; - private readonly Func> _selector; - private readonly Func _resultSelector; - - public LazySelectMany(Lazy lazy, Func> selector, Func resultSelector) => (_lazy, _selector, _resultSelector) = (lazy, selector, resultSelector); - public TResult Apply() { - var first = _lazy.Value; - var second = _selector(first).Value; - return _resultSelector(first, second); + var first = lazy.Value; + var second = selector(first).Value; + return resultSelector(first, second); } } } diff --git a/Funcky/Monads/Option/Option.Debugger.cs b/Funcky/Monads/Option/Option.Debugger.cs index 6c1111d7..b8753b14 100644 --- a/Funcky/Monads/Option/Option.Debugger.cs +++ b/Funcky/Monads/Option/Option.Debugger.cs @@ -13,15 +13,11 @@ public readonly partial struct Option some: _ => "Some"); } -internal sealed class OptionDebugView +internal sealed class OptionDebugView(Option option) where T : notnull { - private readonly Option _option; - - public OptionDebugView(Option option) => _option = option; - [DebuggerBrowsable(RootHidden)] - public object Value => _option.Match( + public object Value => option.Match( none: () => (object)new { }, some: value => new { Value = value }); } diff --git a/Funcky/Monads/Option/OptionComparer.cs b/Funcky/Monads/Option/OptionComparer.cs index 1744a664..2fdca083 100644 --- a/Funcky/Monads/Option/OptionComparer.cs +++ b/Funcky/Monads/Option/OptionComparer.cs @@ -37,17 +37,13 @@ public static Comparer> Create(IComparer comparer) => new OptionComparerInternal(comparer); } -internal sealed class OptionComparerInternal : Comparer> +internal sealed class OptionComparerInternal(IComparer comparer) : Comparer> where TItem : notnull { - private readonly IComparer _comparer; - - internal OptionComparerInternal(IComparer comparer) => _comparer = comparer; - public override int Compare(Option x, Option y) => (x, y).Match( right: _ => ComparisonResult.LessThan, none: () => ComparisonResult.Equal, left: _ => ComparisonResult.GreaterThan, - leftAndRight: _comparer.Compare); + leftAndRight: comparer.Compare); } diff --git a/Funcky/Monads/Option/OptionEqualityComparer.cs b/Funcky/Monads/Option/OptionEqualityComparer.cs index 1ce773c4..c5d78518 100644 --- a/Funcky/Monads/Option/OptionEqualityComparer.cs +++ b/Funcky/Monads/Option/OptionEqualityComparer.cs @@ -31,22 +31,18 @@ public static EqualityComparer> Create(IEqualityComparer new OptionEqualityComparerInternal(comparer); } -internal sealed class OptionEqualityComparerInternal : EqualityComparer> +internal sealed class OptionEqualityComparerInternal(IEqualityComparer comparer) : EqualityComparer> where TItem : notnull { - private readonly IEqualityComparer _comparer; - - internal OptionEqualityComparerInternal(IEqualityComparer comparer) => _comparer = comparer; - public override bool Equals(Option x, Option y) => (x, y).Match( right: False, none: True, left: False, - leftAndRight: _comparer.Equals); + leftAndRight: comparer.Equals); public override int GetHashCode(Option option) => option.Match( none: 0, - some: _comparer.GetHashCode); + some: comparer.GetHashCode); } diff --git a/Funcky/Monads/Option/OptionJsonConverter.cs b/Funcky/Monads/Option/OptionJsonConverter.cs index be1ff44d..974e9c37 100644 --- a/Funcky/Monads/Option/OptionJsonConverter.cs +++ b/Funcky/Monads/Option/OptionJsonConverter.cs @@ -22,21 +22,16 @@ public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializer } } -internal sealed class OptionJsonConverter : JsonConverter> +internal sealed class OptionJsonConverter(JsonConverter itemConverter) : JsonConverter> where TItem : notnull { - private readonly JsonConverter _itemConverter; - - public OptionJsonConverter(JsonConverter itemConverter) - => _itemConverter = itemConverter; - public override Option Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader.TokenType == JsonTokenType.Null ? Option.None - : _itemConverter.Read(ref reader, typeof(TItem), options)!; + : itemConverter.Read(ref reader, typeof(TItem), options)!; public override void Write(Utf8JsonWriter writer, Option value, JsonSerializerOptions options) => value.Switch( none: writer.WriteNullValue, - some: item => _itemConverter.Write(writer, item, options)); + some: item => itemConverter.Write(writer, item, options)); } diff --git a/Funcky/Monads/Result/Result.Debugger.cs b/Funcky/Monads/Result/Result.Debugger.cs index 0c3d0fe4..2af6a22e 100644 --- a/Funcky/Monads/Result/Result.Debugger.cs +++ b/Funcky/Monads/Result/Result.Debugger.cs @@ -13,15 +13,11 @@ public readonly partial struct Result error: _ => "Error"); } -internal sealed class ResultDebugView +internal sealed class ResultDebugView(Result result) where TValidResult : notnull { - private readonly Result _option; - - public ResultDebugView(Result option) => _option = option; - [DebuggerBrowsable(RootHidden)] - public object Value => _option.Match( + public object Value => result.Match( ok: value => (object)new { Value = value }, error: exception => new { Exception = exception }); } diff --git a/Funcky/RetryPolicies/ConstantDelayPolicy.cs b/Funcky/RetryPolicies/ConstantDelayPolicy.cs index b2bea4d8..7d123a83 100644 --- a/Funcky/RetryPolicies/ConstantDelayPolicy.cs +++ b/Funcky/RetryPolicies/ConstantDelayPolicy.cs @@ -1,13 +1,8 @@ namespace Funcky.RetryPolicies; -public class ConstantDelayPolicy : IRetryPolicy +public class ConstantDelayPolicy(int maxRetries, TimeSpan delay) : IRetryPolicy { - private readonly TimeSpan _delay; + public int MaxRetries { get; } = maxRetries; - public ConstantDelayPolicy(int maxRetries, TimeSpan delay) - => (MaxRetries, _delay) = (maxRetries, delay); - - public int MaxRetries { get; } - - public TimeSpan Delay(int retryCount) => _delay; + public TimeSpan Delay(int retryCount) => delay; } diff --git a/Funcky/RetryPolicies/ExponentialBackOffRetryPolicy.cs b/Funcky/RetryPolicies/ExponentialBackOffRetryPolicy.cs index f489de23..8dc52712 100644 --- a/Funcky/RetryPolicies/ExponentialBackOffRetryPolicy.cs +++ b/Funcky/RetryPolicies/ExponentialBackOffRetryPolicy.cs @@ -1,17 +1,13 @@ namespace Funcky.RetryPolicies; -public sealed class ExponentialBackOffRetryPolicy : IRetryPolicy +public sealed class ExponentialBackOffRetryPolicy(int maxRetries, TimeSpan firstDelay) : IRetryPolicy { private const double BaseFactor = 1.5; - private readonly TimeSpan _firstDelay; - public ExponentialBackOffRetryPolicy(int maxRetries, TimeSpan firstDelay) - => (MaxRetries, _firstDelay) = (maxRetries, firstDelay); - - public int MaxRetries { get; } + public int MaxRetries => maxRetries; public TimeSpan Delay(int retryCount) - => _firstDelay.Multiply(Exponential(retryCount)); + => firstDelay.Multiply(Exponential(retryCount)); private static double Exponential(int retryCount) => Math.Pow(BaseFactor, retryCount); diff --git a/Funcky/RetryPolicies/LinearBackOffRetryPolicy.cs b/Funcky/RetryPolicies/LinearBackOffRetryPolicy.cs index 48aa2dd0..db82c0ca 100644 --- a/Funcky/RetryPolicies/LinearBackOffRetryPolicy.cs +++ b/Funcky/RetryPolicies/LinearBackOffRetryPolicy.cs @@ -1,14 +1,9 @@ namespace Funcky.RetryPolicies; -public sealed class LinearBackOffRetryPolicy +public sealed class LinearBackOffRetryPolicy(int maxRetries, TimeSpan firstDelay) : IRetryPolicy { - private readonly TimeSpan _firstDelay; + public int MaxRetries => maxRetries; - public LinearBackOffRetryPolicy(int maxRetries, TimeSpan firstDelay) - => (MaxRetries, _firstDelay) = (maxRetries, firstDelay); - - public int MaxRetries { get; } - - public TimeSpan Delay(int retryCount) => _firstDelay.Multiply(retryCount); + public TimeSpan Delay(int retryCount) => firstDelay.Multiply(retryCount); } diff --git a/Funcky/RetryPolicies/NoDelayRetryPolicy.cs b/Funcky/RetryPolicies/NoDelayRetryPolicy.cs index 2d4151b0..88a5e5c6 100644 --- a/Funcky/RetryPolicies/NoDelayRetryPolicy.cs +++ b/Funcky/RetryPolicies/NoDelayRetryPolicy.cs @@ -1,9 +1,3 @@ namespace Funcky.RetryPolicies; -public sealed class NoDelayRetryPolicy : ConstantDelayPolicy -{ - public NoDelayRetryPolicy(int maxRetries) - : base(maxRetries, TimeSpan.Zero) - { - } -} +public sealed class NoDelayRetryPolicy(int maxRetries) : ConstantDelayPolicy(maxRetries, TimeSpan.Zero); diff --git a/Funcky/Sequence/Sequence.CycleRange.cs b/Funcky/Sequence/Sequence.CycleRange.cs index 7f9c41eb..de09042b 100644 --- a/Funcky/Sequence/Sequence.CycleRange.cs +++ b/Funcky/Sequence/Sequence.CycleRange.cs @@ -20,17 +20,12 @@ public static CycleBuffer Create(IEnumerable source, => new(source, maxCycles); } - private sealed class CycleBuffer : IBuffer + private sealed class CycleBuffer(IEnumerable source, Option maxCycles = default) : IBuffer { private readonly List _buffer = new(); - private readonly IEnumerator _source; - private readonly Option _maxCycles; - + private readonly IEnumerator _source = source.GetEnumerator(); private bool _disposed; - public CycleBuffer(IEnumerable source, Option maxCycles = default) - => (_source, _maxCycles) = (source.GetEnumerator(), maxCycles); - public void Dispose() { if (!_disposed) @@ -83,7 +78,7 @@ private IEnumerator GetEnumeratorInternal() if (_buffer.Count is 0) { - if (_maxCycles.Match(none: true, some: False)) + if (maxCycles.Match(none: true, some: False)) { throw new InvalidOperationException("you cannot cycle an empty enumerable"); } @@ -108,10 +103,10 @@ private IEnumerator GetEnumeratorInternal() } private bool HasNoCycles() - => _maxCycles.Match(none: false, some: maxCycles => maxCycles is 0); + => maxCycles.Match(none: false, some: maxCycles => maxCycles is 0); private bool IsCycling(int cycle) - => _maxCycles.Match( + => maxCycles.Match( none: true, some: maxCycles => cycle < maxCycles);