diff --git a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Internal/TopicMessages.cs b/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Internal/TopicMessages.cs index c053898f476..cbcb0782e02 100644 --- a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Internal/TopicMessages.cs +++ b/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Internal/TopicMessages.cs @@ -424,7 +424,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is SendToOneSubscriber && Equals((SendToOneSubscriber)obj); + return obj is SendToOneSubscriber subscriber && Equals(subscriber); } public override int GetHashCode() diff --git a/src/contrib/cluster/Akka.DistributedData/Durable/Messages.cs b/src/contrib/cluster/Akka.DistributedData/Durable/Messages.cs index 565f6fee404..ecd06a959dd 100644 --- a/src/contrib/cluster/Akka.DistributedData/Durable/Messages.cs +++ b/src/contrib/cluster/Akka.DistributedData/Durable/Messages.cs @@ -125,7 +125,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is DurableDataEnvelope && Equals((DurableDataEnvelope) obj); + return obj is DurableDataEnvelope envelope && Equals(envelope); } } } diff --git a/src/contrib/cluster/Akka.DistributedData/Flag.cs b/src/contrib/cluster/Akka.DistributedData/Flag.cs index 813006fbfb2..eeb8a918b6b 100644 --- a/src/contrib/cluster/Akka.DistributedData/Flag.cs +++ b/src/contrib/cluster/Akka.DistributedData/Flag.cs @@ -65,11 +65,11 @@ public bool Equals(Flag other) } - public override bool Equals(object obj) => obj is Flag && Equals((Flag) obj); + public override bool Equals(object obj) => obj is Flag flag && Equals(flag); public override int GetHashCode() => Enabled.GetHashCode(); - public int CompareTo(object obj) => obj is Flag ? CompareTo((Flag) obj) : 1; + public int CompareTo(object obj) => obj is Flag flag ? CompareTo(flag) : 1; public int CompareTo(Flag other) => other == null ? 1 : Enabled.CompareTo(other.Enabled); diff --git a/src/contrib/cluster/Akka.DistributedData/GSet.cs b/src/contrib/cluster/Akka.DistributedData/GSet.cs index 3808496d617..a8067c87875 100644 --- a/src/contrib/cluster/Akka.DistributedData/GSet.cs +++ b/src/contrib/cluster/Akka.DistributedData/GSet.cs @@ -162,7 +162,7 @@ public bool Equals(GSet other) public IEnumerator GetEnumerator() => Elements.GetEnumerator(); - public override bool Equals(object obj) => obj is GSet && Equals((GSet)obj); + public override bool Equals(object obj) => obj is GSet set && Equals(set); public override int GetHashCode() diff --git a/src/contrib/cluster/Akka.DistributedData/Internal/Internal.cs b/src/contrib/cluster/Akka.DistributedData/Internal/Internal.cs index 0c621b70c30..dc1b782188b 100644 --- a/src/contrib/cluster/Akka.DistributedData/Internal/Internal.cs +++ b/src/contrib/cluster/Akka.DistributedData/Internal/Internal.cs @@ -137,7 +137,7 @@ public bool Equals(Write other) } /// - public override bool Equals(object obj) => obj is Write && Equals((Write)obj); + public override bool Equals(object obj) => obj is Write write && Equals(write); /// public override int GetHashCode() @@ -245,7 +245,7 @@ public bool Equals(Read other) } /// - public override bool Equals(object obj) => obj is Read && Equals((Read)obj); + public override bool Equals(object obj) => obj is Read read && Equals(read); /// public override int GetHashCode() => Key?.GetHashCode() ?? 0; @@ -284,7 +284,7 @@ public bool Equals(ReadResult other) } /// - public override bool Equals(object obj) => obj is ReadResult && Equals((ReadResult)obj); + public override bool Equals(object obj) => obj is ReadResult result && Equals(result); /// public override int GetHashCode() => Envelope?.GetHashCode() ?? 0; @@ -329,7 +329,7 @@ public bool Equals(ReadRepair other) } /// - public override bool Equals(object obj) => obj is ReadRepair && Equals((ReadRepair)obj); + public override bool Equals(object obj) => obj is ReadRepair repair && Equals(repair); /// public override int GetHashCode() @@ -715,7 +715,7 @@ public bool Equals(Status other) } /// - public override bool Equals(object obj) => obj is Status && Equals((Status)obj); + public override bool Equals(object obj) => obj is Status status && Equals(status); /// public override int GetHashCode() @@ -795,7 +795,7 @@ public bool Equals(Gossip other) } /// - public override bool Equals(object obj) => obj is Gossip && Equals((Gossip)obj); + public override bool Equals(object obj) => obj is Gossip gossip && Equals(gossip); /// public override int GetHashCode() @@ -847,7 +847,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Delta && Equals((Delta)obj); + return obj is Delta delta && Equals(delta); } public override int GetHashCode() @@ -920,7 +920,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is DeltaPropagation && Equals((DeltaPropagation)obj); + return obj is DeltaPropagation propagation && Equals(propagation); } public override int GetHashCode() diff --git a/src/contrib/cluster/Akka.DistributedData/LWWDictionary.cs b/src/contrib/cluster/Akka.DistributedData/LWWDictionary.cs index 9d1f5fc4823..ab877d55865 100644 --- a/src/contrib/cluster/Akka.DistributedData/LWWDictionary.cs +++ b/src/contrib/cluster/Akka.DistributedData/LWWDictionary.cs @@ -324,7 +324,7 @@ public IEnumerator> GetEnumerator() => public override bool Equals(object obj) => - obj is LWWDictionary && Equals((LWWDictionary)obj); + obj is LWWDictionary pairs && Equals(pairs); public override int GetHashCode() => Underlying.GetHashCode(); diff --git a/src/contrib/cluster/Akka.DistributedData/LWWRegister.cs b/src/contrib/cluster/Akka.DistributedData/LWWRegister.cs index b1907fc14a9..30efd6c5a92 100644 --- a/src/contrib/cluster/Akka.DistributedData/LWWRegister.cs +++ b/src/contrib/cluster/Akka.DistributedData/LWWRegister.cs @@ -198,7 +198,7 @@ public bool Equals(LWWRegister other) } - public override bool Equals(object obj) => obj is LWWRegister && Equals((LWWRegister)obj); + public override bool Equals(object obj) => obj is LWWRegister register && Equals(register); public override int GetHashCode() diff --git a/src/contrib/cluster/Akka.DistributedData/ORMultiValueDictionary.cs b/src/contrib/cluster/Akka.DistributedData/ORMultiValueDictionary.cs index 1b875cf76ef..d1ddc5b1356 100644 --- a/src/contrib/cluster/Akka.DistributedData/ORMultiValueDictionary.cs +++ b/src/contrib/cluster/Akka.DistributedData/ORMultiValueDictionary.cs @@ -282,7 +282,7 @@ public IEnumerator>> GetEnumerator() => Underlying.Select(x => new KeyValuePair>(x.Key, x.Value.Elements)).GetEnumerator(); public override bool Equals(object obj) => - obj is ORMultiValueDictionary && Equals((ORMultiValueDictionary)obj); + obj is ORMultiValueDictionary pairs && Equals(pairs); public override int GetHashCode() => Underlying.GetHashCode(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); diff --git a/src/contrib/cluster/Akka.DistributedData/ORSet.cs b/src/contrib/cluster/Akka.DistributedData/ORSet.cs index b1bcdb75bce..8e69e166aac 100644 --- a/src/contrib/cluster/Akka.DistributedData/ORSet.cs +++ b/src/contrib/cluster/Akka.DistributedData/ORSet.cs @@ -446,7 +446,7 @@ public bool Equals(ORSet other) IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public override bool Equals(object obj) => obj is ORSet && Equals((ORSet)obj); + public override bool Equals(object obj) => obj is ORSet set && Equals(set); public override int GetHashCode() @@ -570,9 +570,9 @@ public override IReplicatedData Merge(IReplicatedData other) { return new DeltaGroup(ImmutableArray.Create(this, other)); } - else if (other is DeltaGroup) + else if (other is DeltaGroup group) { - var vector = ((DeltaGroup)other).Operations; + var vector = group.Operations; return new DeltaGroup(vector.Add(this)); } else throw new ArgumentException($"Unknown delta operation of type {other.GetType()}", nameof(other)); @@ -593,9 +593,9 @@ public override IReplicatedData Merge(IReplicatedData other) { return new DeltaGroup(ImmutableArray.Create(this, other)); } - else if (other is DeltaGroup) + else if (other is DeltaGroup group) { - var vector = ((DeltaGroup)other).Operations; + var vector = group.Operations; return new DeltaGroup(vector.Add(this)); } else throw new ArgumentException($"Unknown delta operation of type {other.GetType()}", nameof(other)); @@ -650,7 +650,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is DeltaGroup && Equals((DeltaGroup)obj); + return obj is DeltaGroup group && Equals(group); } public override int GetHashCode() diff --git a/src/contrib/cluster/Akka.DistributedData/PNCounter.cs b/src/contrib/cluster/Akka.DistributedData/PNCounter.cs index 83f63b4732e..40c84e6162d 100644 --- a/src/contrib/cluster/Akka.DistributedData/PNCounter.cs +++ b/src/contrib/cluster/Akka.DistributedData/PNCounter.cs @@ -113,7 +113,7 @@ public bool Equals(PNCounter other) public override string ToString() => $"PNCounter({Value})"; - public override bool Equals(object obj) => obj is PNCounter && Equals((PNCounter)obj); + public override bool Equals(object obj) => obj is PNCounter counter && Equals(counter); public override int GetHashCode() => Increments.GetHashCode() ^ Decrements.GetHashCode(); diff --git a/src/contrib/cluster/Akka.DistributedData/ReadAggregator.cs b/src/contrib/cluster/Akka.DistributedData/ReadAggregator.cs index 340b31f7f52..a2bb7143d16 100644 --- a/src/contrib/cluster/Akka.DistributedData/ReadAggregator.cs +++ b/src/contrib/cluster/Akka.DistributedData/ReadAggregator.cs @@ -192,7 +192,7 @@ public ReadFrom(int n, TimeSpan timeout) } - public override bool Equals(object obj) => obj is ReadFrom && Equals((ReadFrom) obj); + public override bool Equals(object obj) => obj is ReadFrom from && Equals(from); public bool Equals(ReadFrom other) @@ -229,7 +229,7 @@ public ReadMajority(TimeSpan timeout, int minCapacity = 0) public override bool Equals(object obj) { - return obj is ReadMajority && Equals((ReadMajority) obj); + return obj is ReadMajority majority && Equals(majority); } @@ -274,7 +274,7 @@ public ReadMajorityPlus(TimeSpan timeout, int additional, int minCapacity = 0) public override bool Equals(object obj) { - return obj is ReadMajorityPlus && Equals((ReadMajorityPlus)obj); + return obj is ReadMajorityPlus plus && Equals(plus); } @@ -314,7 +314,7 @@ public ReadAll(TimeSpan timeout) public override bool Equals(object obj) { - return obj is ReadAll && Equals((ReadAll) obj); + return obj is ReadAll all && Equals(all); } diff --git a/src/contrib/cluster/Akka.DistributedData/Replicator.Messages.cs b/src/contrib/cluster/Akka.DistributedData/Replicator.Messages.cs index 24bf65b04a8..272a9b8b94b 100644 --- a/src/contrib/cluster/Akka.DistributedData/Replicator.Messages.cs +++ b/src/contrib/cluster/Akka.DistributedData/Replicator.Messages.cs @@ -40,7 +40,7 @@ public GetKeysIdsResult(IImmutableSet keys) public override bool Equals(object obj) => - obj is GetKeysIdsResult && Equals((GetKeysIdsResult)obj); + obj is GetKeysIdsResult result && Equals(result); public bool Equals(GetKeysIdsResult other) @@ -96,7 +96,7 @@ public bool Equals(Get other) } - public override bool Equals(object obj) => obj is Get && Equals((Get)obj); + public override bool Equals(object obj) => obj is Get get && Equals(get); public override int GetHashCode() @@ -191,7 +191,7 @@ public bool Equals(GetSuccess other) } - public override bool Equals(object obj) => obj is GetSuccess && Equals((GetSuccess)obj); + public override bool Equals(object obj) => obj is GetSuccess success && Equals(success); public override int GetHashCode() @@ -211,7 +211,7 @@ public override int GetHashCode() public T Get(IKey key) where T : IReplicatedData { - if (Data is T) return (T)Data; + if (Data is T data) return data; throw new InvalidCastException($"Response returned for key '{Key}' is of type [{Data?.GetType()}] and cannot be casted using key '{key}' to type [{typeof(T)}]"); } @@ -242,7 +242,7 @@ public bool Equals(NotFound other) } - public override bool Equals(object obj) => obj is NotFound && Equals((NotFound)obj); + public override bool Equals(object obj) => obj is NotFound found && Equals(found); public override string ToString() => $"NotFound({Key}{(Request == null ? "" : ", req=" + Request)})"; @@ -292,7 +292,7 @@ public bool Equals(GetFailure other) } - public override bool Equals(object obj) => obj is GetFailure && Equals((GetFailure)obj); + public override bool Equals(object obj) => obj is GetFailure failure && Equals(failure); public override int GetHashCode() @@ -352,7 +352,7 @@ public bool Equals(Subscribe other) } - public override bool Equals(object obj) => obj is Subscribe && Equals((Subscribe)obj); + public override bool Equals(object obj) => obj is Subscribe subscribe && Equals(subscribe); public override int GetHashCode() @@ -393,7 +393,7 @@ public bool Equals(Unsubscribe other) } - public override bool Equals(object obj) => obj is Unsubscribe && Equals((Unsubscribe)obj); + public override bool Equals(object obj) => obj is Unsubscribe unsubscribe && Equals(unsubscribe); public override int GetHashCode() @@ -448,7 +448,7 @@ public T Get(IKey key) where T : IReplicatedData } - public override bool Equals(object obj) => obj is Changed && Equals((Changed)obj); + public override bool Equals(object obj) => obj is Changed changed && Equals(changed); public override int GetHashCode() @@ -572,7 +572,7 @@ public bool Equals(UpdateSuccess other) } - public override bool Equals(object obj) => obj is UpdateSuccess && Equals((UpdateSuccess)obj); + public override bool Equals(object obj) => obj is UpdateSuccess success && Equals(success); public override int GetHashCode() @@ -631,7 +631,7 @@ public bool Equals(UpdateTimeout other) } - public override bool Equals(object obj) => obj is UpdateTimeout && Equals((UpdateTimeout)obj); + public override bool Equals(object obj) => obj is UpdateTimeout timeout && Equals(timeout); public override string ToString() => $"UpdateTimeout({Key}{(Request == null ? "" : ", req=" + Request)})"; @@ -738,7 +738,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is StoreFailure && Equals((StoreFailure)obj); + return obj is StoreFailure failure && Equals(failure); } @@ -779,7 +779,7 @@ public bool Equals(Delete other) } - public override bool Equals(object obj) => obj is Delete && Equals((Delete)obj); + public override bool Equals(object obj) => obj is Delete delete && Equals(delete); public override int GetHashCode() @@ -853,7 +853,7 @@ public bool Equals(DeleteSuccess other) } - public override bool Equals(object obj) => obj is DeleteSuccess && Equals((DeleteSuccess)obj); + public override bool Equals(object obj) => obj is DeleteSuccess success && Equals(success); public override int GetHashCode() => Key.GetHashCode(); @@ -884,7 +884,7 @@ public bool Equals(ReplicationDeleteFailure other) } - public override bool Equals(object obj) => obj is ReplicationDeleteFailure && Equals((ReplicationDeleteFailure)obj); + public override bool Equals(object obj) => obj is ReplicationDeleteFailure failure && Equals(failure); public override int GetHashCode() => Key.GetHashCode(); @@ -920,7 +920,7 @@ public bool Equals(DataDeleted other) } - public override bool Equals(object obj) => obj is DataDeleted && Equals((DataDeleted)obj); + public override bool Equals(object obj) => obj is DataDeleted deleted && Equals(deleted); public override int GetHashCode() => Key.GetHashCode(); @@ -967,7 +967,7 @@ public ReplicaCount(int n) public bool Equals(ReplicaCount other) => other != null && N == other.N; - public override bool Equals(object obj) => obj is ReplicaCount && Equals((ReplicaCount)obj); + public override bool Equals(object obj) => obj is ReplicaCount count && Equals(count); public override int GetHashCode() => N.GetHashCode(); diff --git a/src/contrib/persistence/Akka.Persistence.Sql.Common/Snapshot/QueryExecutor.cs b/src/contrib/persistence/Akka.Persistence.Sql.Common/Snapshot/QueryExecutor.cs index 30aa3aa718f..0d79992f003 100644 --- a/src/contrib/persistence/Akka.Persistence.Sql.Common/Snapshot/QueryExecutor.cs +++ b/src/contrib/persistence/Akka.Persistence.Sql.Common/Snapshot/QueryExecutor.cs @@ -429,9 +429,9 @@ protected virtual void SetManifestParameters(object snapshot, DbCommand command) var serializer = Serialization.FindSerializerForType(snapshotType); string manifest = ""; - if (serializer is SerializerWithStringManifest) + if (serializer is SerializerWithStringManifest stringManifest) { - manifest = ((SerializerWithStringManifest)serializer).Manifest(snapshot); + manifest = stringManifest.Manifest(snapshot); } else { diff --git a/src/core/Akka.Cluster.Tests.MultiNode/Routing/ClusterRoundRobinSpec.cs b/src/core/Akka.Cluster.Tests.MultiNode/Routing/ClusterRoundRobinSpec.cs index 5eaa38da421..c49e5ff72b4 100644 --- a/src/core/Akka.Cluster.Tests.MultiNode/Routing/ClusterRoundRobinSpec.cs +++ b/src/core/Akka.Cluster.Tests.MultiNode/Routing/ClusterRoundRobinSpec.cs @@ -437,7 +437,7 @@ private void A_cluster_router_with_a_RoundRobin_router_must_deploy_programatical var notUsedAddress = Roles.Select(c => GetAddress(c)).Except(routeeAddresses()).First(); var downAddress = routeeAddresses().Find(c => c != GetAddress(_config.First)); var downRouteeRef = routees() - .Where(c => c is ActorRefRoutee && ((ActorRefRoutee)c).Actor.Path.Address == downAddress) + .Where(c => c is ActorRefRoutee routee && routee.Actor.Path.Address == downAddress) .Select(c => ((ActorRefRoutee)c).Actor).First(); Cluster.Down(downAddress); diff --git a/src/core/Akka.Cluster/AutoDown.cs b/src/core/Akka.Cluster/AutoDown.cs index 4fb023f5c5d..9967e65ff84 100644 --- a/src/core/Akka.Cluster/AutoDown.cs +++ b/src/core/Akka.Cluster/AutoDown.cs @@ -67,7 +67,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is UnreachableTimeout && Equals((UnreachableTimeout)obj); + return obj is UnreachableTimeout timeout && Equals(timeout); } /// diff --git a/src/core/Akka.Cluster/ClusterDaemon.cs b/src/core/Akka.Cluster/ClusterDaemon.cs index bea1b4df4eb..aeb504e849e 100644 --- a/src/core/Akka.Cluster/ClusterDaemon.cs +++ b/src/core/Akka.Cluster/ClusterDaemon.cs @@ -166,7 +166,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Join && Equals((Join)obj); + return obj is Join join && Equals(join); } private bool Equals(Join other) @@ -330,7 +330,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is InitJoinAck && Equals((InitJoinAck)obj); + return obj is InitJoinAck ack && Equals(ack); } private bool Equals(InitJoinAck other) @@ -372,7 +372,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is InitJoinNack && Equals((InitJoinNack)obj); + return obj is InitJoinNack nack && Equals(nack); } private bool Equals(InitJoinNack other) @@ -412,7 +412,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is ExitingConfirmed && Equals((ExitingConfirmed)obj); + return obj is ExitingConfirmed confirmed && Equals(confirmed); } /// diff --git a/src/core/Akka.Docs.Tests/Networking/IO/EchoConnection.cs b/src/core/Akka.Docs.Tests/Networking/IO/EchoConnection.cs index 891551ef0bd..48a57296912 100644 --- a/src/core/Akka.Docs.Tests/Networking/IO/EchoConnection.cs +++ b/src/core/Akka.Docs.Tests/Networking/IO/EchoConnection.cs @@ -23,9 +23,8 @@ public EchoConnection(IActorRef connection) protected override void OnReceive(object message) { - if (message is Tcp.Received) + if (message is Tcp.Received received) { - var received = message as Tcp.Received; if (received.Data[0] == 'x') Context.Stop(Self); else diff --git a/src/core/Akka.Docs.Tests/Networking/IO/EchoServer.cs b/src/core/Akka.Docs.Tests/Networking/IO/EchoServer.cs index 3cced729669..6b6ad61b138 100644 --- a/src/core/Akka.Docs.Tests/Networking/IO/EchoServer.cs +++ b/src/core/Akka.Docs.Tests/Networking/IO/EchoServer.cs @@ -22,9 +22,8 @@ public EchoServer(int port) protected override void OnReceive(object message) { - if (message is Tcp.Bound) + if (message is Tcp.Bound bound) { - var bound = message as Tcp.Bound; Console.WriteLine("Listening on {0}", bound.LocalAddress); } else if (message is Tcp.Connected) diff --git a/src/core/Akka.Docs.Tests/Networking/IO/TelnetClient.cs b/src/core/Akka.Docs.Tests/Networking/IO/TelnetClient.cs index c8fd28eb8c5..cd0ecc65f70 100644 --- a/src/core/Akka.Docs.Tests/Networking/IO/TelnetClient.cs +++ b/src/core/Akka.Docs.Tests/Networking/IO/TelnetClient.cs @@ -25,9 +25,8 @@ public TelnetClient(string host, int port) protected override void OnReceive(object message) { - if (message is Tcp.Connected) + if (message is Tcp.Connected connected) { - var connected = message as Tcp.Connected; Console.WriteLine("Connected to {0}", connected.RemoteAddress); // Register self as connection handler @@ -46,14 +45,13 @@ private UntypedReceive Connected(IActorRef connection) { return message => { - if (message is Tcp.Received) // data received from network + if (message is Tcp.Received received) // data received from network { - var received = message as Tcp.Received; Console.WriteLine(Encoding.ASCII.GetString(received.Data.ToArray())); } - else if (message is string) // data received from console + else if (message is string s) // data received from console { - connection.Tell(Tcp.Write.Create(ByteString.FromString((string)message + "\n"))); + connection.Tell(Tcp.Write.Create(ByteString.FromString(s + "\n"))); ReadConsoleAsync(); } else if (message is Tcp.PeerClosed) diff --git a/src/core/Akka.Docs.Tests/Persistence/PersistentActor/PersistentActor.cs b/src/core/Akka.Docs.Tests/Persistence/PersistentActor/PersistentActor.cs index 246bbb69b27..f0dd3c6bbec 100644 --- a/src/core/Akka.Docs.Tests/Persistence/PersistentActor/PersistentActor.cs +++ b/src/core/Akka.Docs.Tests/Persistence/PersistentActor/PersistentActor.cs @@ -78,8 +78,8 @@ protected override void OnRecover(object message) case Evt evt: UpdateState(evt); break; - case SnapshotOffer snapshot when snapshot.Snapshot is ExampleState: - _state = (ExampleState)snapshot.Snapshot; + case SnapshotOffer snapshot when snapshot.Snapshot is ExampleState state: + _state = state; break; } } diff --git a/src/core/Akka.Persistence.Query/Offset.cs b/src/core/Akka.Persistence.Query/Offset.cs index 020d7ce25ae..8151f3b81cc 100644 --- a/src/core/Akka.Persistence.Query/Offset.cs +++ b/src/core/Akka.Persistence.Query/Offset.cs @@ -69,7 +69,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Sequence && Equals((Sequence)obj); + return obj is Sequence sequence && Equals(sequence); } public override int GetHashCode() => Value.GetHashCode(); diff --git a/src/core/Akka.Persistence.TCK/Serialization/JournalSerializationSpec.cs b/src/core/Akka.Persistence.TCK/Serialization/JournalSerializationSpec.cs index dea26ee106d..fa574a45ec0 100644 --- a/src/core/Akka.Persistence.TCK/Serialization/JournalSerializationSpec.cs +++ b/src/core/Akka.Persistence.TCK/Serialization/JournalSerializationSpec.cs @@ -193,8 +193,8 @@ public MyPayload2Serializer(ExtendedActorSystem system) : base(system) public override byte[] ToBinary(object obj) { - if (obj is MyPayload2) - return Encoding.UTF8.GetBytes(string.Format(".{0}:{1}", ((MyPayload2)obj).Data, ((MyPayload2)obj).N)); + if (obj is MyPayload2 payload2) + return Encoding.UTF8.GetBytes(string.Format(".{0}:{1}", payload2.Data, payload2.N)); return null; } diff --git a/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryCrashSpec.cs b/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryCrashSpec.cs index 6b5de585397..684282aca7f 100644 --- a/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryCrashSpec.cs +++ b/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryCrashSpec.cs @@ -104,8 +104,8 @@ protected override bool ReceiveRecover(object message) protected override bool ReceiveCommand(object message) { - if (message is Message) Persist(message as Message, _ => Send()); - else if (message is CrashMessage) Persist(message as CrashMessage, _ => { }); + if (message is Message message1) Persist(message1, _ => Send()); + else if (message is CrashMessage crashMessage) Persist(crashMessage, _ => { }); else return false; return true; } diff --git a/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryFailureSpec.cs b/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryFailureSpec.cs index 81b5161323f..ed586996b0a 100644 --- a/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryFailureSpec.cs +++ b/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryFailureSpec.cs @@ -199,15 +199,13 @@ protected override bool ReceiveCommand(object message) private void UpdateState(IEvt evt) { - if (evt is MsgSent) + if (evt is MsgSent msg) { - var msg = (MsgSent)evt; Add(msg.I); Deliver(_destination.Path, deliveryId => new Msg(deliveryId, msg.I)); } - else if (evt is MsgConfirmed) + else if (evt is MsgConfirmed confirmation) { - var confirmation = (MsgConfirmed)evt; ConfirmDelivery(confirmation.DeliveryId); } } diff --git a/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryReceiveActorSpec.cs b/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryReceiveActorSpec.cs index 7285b038342..67084f971ba 100644 --- a/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryReceiveActorSpec.cs +++ b/src/core/Akka.Persistence.Tests/AtLeastOnceDeliveryReceiveActorSpec.cs @@ -56,7 +56,7 @@ public bool Equals(Action other) public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; - return obj is Action && Equals((Action) obj); + return obj is Action action && Equals(action); } public override int GetHashCode() @@ -585,8 +585,8 @@ public void PersistentReceive_must_warn_about_unconfirmed_messages() ExpectMsg(ReqAck.Instance); UnconfirmedDelivery[] unconfirmed = ReceiveWhile(TimeSpan.FromSeconds(3), x => - x is UnconfirmedWarning - ? ((UnconfirmedWarning) x).UnconfirmedDeliveries + x is UnconfirmedWarning warning + ? warning.UnconfirmedDeliveries : Enumerable.Empty()) .SelectMany(e => e).ToArray(); diff --git a/src/core/Akka.Persistence.Tests/AtLeastOnceDeliverySpec.cs b/src/core/Akka.Persistence.Tests/AtLeastOnceDeliverySpec.cs index 322d7888992..03d2208eabd 100644 --- a/src/core/Akka.Persistence.Tests/AtLeastOnceDeliverySpec.cs +++ b/src/core/Akka.Persistence.Tests/AtLeastOnceDeliverySpec.cs @@ -300,7 +300,7 @@ public Action(long id, string payload) public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; - return obj is Action && Equals((Action)obj); + return obj is Action action && Equals(action); } public bool Equals(Action other) { diff --git a/src/core/Akka.Persistence.Tests/EndToEndEventAdapterSpec.cs b/src/core/Akka.Persistence.Tests/EndToEndEventAdapterSpec.cs index 0f37e3e95b8..4c23d31d4fe 100644 --- a/src/core/Akka.Persistence.Tests/EndToEndEventAdapterSpec.cs +++ b/src/core/Akka.Persistence.Tests/EndToEndEventAdapterSpec.cs @@ -111,7 +111,7 @@ public string Manifest(object evt) public object ToJournal(object evt) { - if (evt is IAppModel) return new Json((evt as IAppModel).Payload); + if (evt is IAppModel model) return new Json(model.Payload); return null; } @@ -138,7 +138,7 @@ public string Manifest(object evt) public object ToJournal(object evt) { - if (evt is IAppModel) return new Json((evt as IAppModel).Payload); + if (evt is IAppModel model) return new Json(model.Payload); return null; } @@ -165,7 +165,7 @@ public string Manifest(object evt) public object ToJournal(object evt) { - if (evt is IAppModel) return new Json((evt as IAppModel).Payload); + if (evt is IAppModel model) return new Json(model.Payload); return null; } @@ -192,7 +192,7 @@ public string Manifest(object evt) public object ToJournal(object evt) { - if (evt is IAppModel) return new Json((evt as IAppModel).Payload); + if (evt is IAppModel model) return new Json(model.Payload); return null; } diff --git a/src/core/Akka.Persistence.Tests/PersistentActorDeleteFailureSpec.cs b/src/core/Akka.Persistence.Tests/PersistentActorDeleteFailureSpec.cs index 4a3a06ff409..720352ee656 100644 --- a/src/core/Akka.Persistence.Tests/PersistentActorDeleteFailureSpec.cs +++ b/src/core/Akka.Persistence.Tests/PersistentActorDeleteFailureSpec.cs @@ -66,9 +66,9 @@ protected override bool ReceiveRecover(object message) protected override bool ReceiveCommand(object message) { - if (message is DeleteTo) + if (message is DeleteTo to) { - DeleteMessages(((DeleteTo)message).N); + DeleteMessages(to.N); return true; } return false; @@ -95,8 +95,8 @@ protected override bool ReceiveRecover(object message) protected override bool ReceiveCommand(object message) { - if (message is DeleteTo) - DeleteMessages(((DeleteTo)message).N); + if (message is DeleteTo to) + DeleteMessages(to.N); if (message is DeleteMessagesFailure) _probe.Tell(message); else return false; diff --git a/src/core/Akka.Persistence.Tests/PersistentActorFailureSpec.cs b/src/core/Akka.Persistence.Tests/PersistentActorFailureSpec.cs index d33a8082e5f..9362dd03102 100644 --- a/src/core/Akka.Persistence.Tests/PersistentActorFailureSpec.cs +++ b/src/core/Akka.Persistence.Tests/PersistentActorFailureSpec.cs @@ -210,9 +210,9 @@ protected override bool ReceiveCommand(object message) private bool FailingRecover(object message) { - if (message is Evt) + if (message is Evt evt) { - if (((Evt) message).Data.Equals("bad")) + if (evt.Data.Equals("bad")) throw new SimulatedException("Simulated exception from receiveRecover"); } return true; diff --git a/src/core/Akka.Persistence.Tests/PersistentActorJournalProtocolSpec.cs b/src/core/Akka.Persistence.Tests/PersistentActorJournalProtocolSpec.cs index c61860c3106..613f85ba9e6 100644 --- a/src/core/Akka.Persistence.Tests/PersistentActorJournalProtocolSpec.cs +++ b/src/core/Akka.Persistence.Tests/PersistentActorJournalProtocolSpec.cs @@ -220,9 +220,9 @@ protected override bool ReceiveCommand(object message) { if (!Behavior(message)) { - if (message is Multi) + if (message is Multi multi) { - foreach (var command in ((Multi) message).Commands) + foreach (var command in multi.Commands) Behavior(command); return true; } @@ -233,14 +233,14 @@ protected override bool ReceiveCommand(object message) private bool Behavior(object message) { - if (message is Persist) - P((Persist) message); - else if (message is PersistAsync) - PA((PersistAsync) message); - else if (message is Echo) - Sender.Tell(new Done(((Echo) message).Id, 0)); - else if (message is Fail) - throw ((Fail) message).Exception; + if (message is Persist persist) + P(persist); + else if (message is PersistAsync async) + PA(async); + else if (message is Echo echo) + Sender.Tell(new Done(echo.Id, 0)); + else if (message is Fail fail) + throw fail.Exception; else return false; return true; } @@ -349,9 +349,8 @@ private WriteMessages ExpectWrite(IActorRef subject, params Msgs[] msgs) { var message = messages[i]; var msg = msgs[i]; - if (message is AtomicWrite) + if (message is AtomicWrite aw) { - var aw = ((AtomicWrite) message); var writes = ((IEnumerable) aw.Payload).ToList(); writes.Count.ShouldBe(msg.Messages.Count); for (int j = 0; j < writes.Count; j++) @@ -371,9 +370,9 @@ private void Confirm(WriteMessages w) _journal.Send(w.PersistentActor, WriteMessagesSuccessful.Instance); foreach (var message in w.Messages) { - if (message is AtomicWrite) + if (message is AtomicWrite write) { - var msgs = (IEnumerable) ((AtomicWrite) message).Payload; + var msgs = (IEnumerable) write.Payload; foreach (var msg in msgs) { w.PersistentActor.Tell(new WriteMessageSuccess(msg, w.ActorInstanceId), msg.Sender); diff --git a/src/core/Akka.Persistence.Tests/PersistentActorSpec.Actors.cs b/src/core/Akka.Persistence.Tests/PersistentActorSpec.Actors.cs index c0f9e7f5c40..5793d565419 100644 --- a/src/core/Akka.Persistence.Tests/PersistentActorSpec.Actors.cs +++ b/src/core/Akka.Persistence.Tests/PersistentActorSpec.Actors.cs @@ -28,9 +28,8 @@ protected override bool ReceiveCommand(object message) protected bool Receiver(object message) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; PersistAll(new[] { new Evt(cmd.Data + "-1"), new Evt(cmd.Data + "-2") }, UpdateStateHandler); } else if (message is DeleteMessagesSuccess) @@ -52,16 +51,16 @@ protected bool Receiver(object message) protected override void OnPersistRejected(Exception cause, object @event, long sequenceNr) { - if (@event is Evt) - Sender.Tell("Rejected: " + ((Evt)@event).Data); + if (@event is Evt evt) + Sender.Tell("Rejected: " + evt.Data); else base.OnPersistRejected(cause, @event, sequenceNr); } protected override void OnPersistFailure(Exception cause, object @event, long sequenceNr) { - if (@event is Evt) - Sender.Tell("Failure: " + ((Evt)@event).Data); + if (@event is Evt evt) + Sender.Tell("Failure: " + evt.Data); else base.OnPersistFailure(cause, @event, sequenceNr); } @@ -148,10 +147,10 @@ protected override bool ReceiveRecover(object message) protected bool UpdateState(object message) { - if (message is Evt) - Events = Events.AddFirst((message as Evt).Data); - else if (message is IActorRef) - AskedForDelete = (IActorRef)message; + if (message is Evt evt) + Events = Events.AddFirst(evt.Data); + else if (message is IActorRef @ref) + AskedForDelete = @ref; else return false; return true; @@ -161,10 +160,10 @@ protected bool CommonBehavior(object message) { if (message is GetState) Sender.Tell(Events.Reverse().ToArray()); else if (message.ToString() == "boom") throw new TestException("boom"); - else if (message is Delete) + else if (message is Delete delete) { Persist(Sender, s => AskedForDelete = s); - DeleteMessages(((Delete)message).ToSequenceNr); + DeleteMessages(delete.ToSequenceNr); } else return false; return true; @@ -183,9 +182,8 @@ protected override bool ReceiveCommand(object message) protected bool Receiver(object message) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; PersistAll(new[] { new Evt(cmd.Data + "-1"), new Evt(cmd.Data + "-2") }, UpdateStateHandler); PersistAll(new[] { new Evt(cmd.Data + "-3"), new Evt(cmd.Data + "-4") }, UpdateStateHandler); return true; @@ -204,9 +202,8 @@ protected override bool ReceiveCommand(object message) protected bool Receiver(object message) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; PersistAll(new[] { new Evt(cmd.Data + "-11"), new Evt(cmd.Data + "-12") }, UpdateStateHandler); UpdateState(new Evt(cmd.Data + "-10")); return true; @@ -223,9 +220,8 @@ protected override bool ReceiveCommand(object message) { if (CommonBehavior(message)) return true; - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; Persist(new Evt(cmd.Data + "-0"), evt => { UpdateState(evt); @@ -238,10 +234,8 @@ protected override bool ReceiveCommand(object message) protected bool NewBehavior(object message) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; - Persist(new Evt(cmd.Data + "-21"), UpdateStateHandler); Persist(new Evt(cmd.Data + "-22"), evt => { @@ -262,9 +256,8 @@ protected override bool ReceiveCommand(object message) { if (CommonBehavior(message)) return true; - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; Persist(new Evt(cmd.Data + "-0"), evt => { UpdateState(evt); @@ -277,10 +270,8 @@ protected override bool ReceiveCommand(object message) protected bool NewBehavior(object message) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; - Persist(new Evt(cmd.Data + "-21"), evt => { UpdateState(evt); @@ -300,9 +291,8 @@ protected override bool ReceiveCommand(object message) { if (CommonBehavior(message)) return true; - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; Context.Become(NewBehavior); Persist(new Evt(cmd.Data + "-0"), UpdateStateHandler); return true; @@ -312,9 +302,8 @@ protected override bool ReceiveCommand(object message) protected bool NewBehavior(object message) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; Context.UnbecomeStacked(); PersistAll(new[] { new Evt(cmd.Data + "-31"), new Evt(cmd.Data + "-32") }, UpdateStateHandler); UpdateState(new Evt(cmd.Data + "-30")); @@ -332,9 +321,8 @@ protected override bool ReceiveCommand(object message) { if (CommonBehavior(message)) return true; - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; Persist(new Evt(cmd.Data + "-0"), UpdateStateHandler); Context.Become(NewBehavior); return true; @@ -344,9 +332,8 @@ protected override bool ReceiveCommand(object message) protected bool NewBehavior(object message) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; PersistAll(new[] { new Evt(cmd.Data + "-31"), new Evt(cmd.Data + "-32") }, UpdateStateHandler); UpdateState(new Evt(cmd.Data + "-30")); Context.UnbecomeStacked(); @@ -369,10 +356,10 @@ protected override bool ReceiveRecover(object message) { if (!base.ReceiveRecover(message)) { - if (message is SnapshotOffer) + if (message is SnapshotOffer offer) { Probe.Tell("offered"); - Events = (message as SnapshotOffer).Snapshot.AsInstanceOf>(); + Events = offer.Snapshot.AsInstanceOf>(); } else return false; } @@ -382,7 +369,7 @@ protected override bool ReceiveRecover(object message) protected override bool ReceiveCommand(object message) { if (CommonBehavior(message)) return true; - if (message is Cmd) HandleCmd(message as Cmd); + if (message is Cmd cmd) HandleCmd(cmd); else if (message is SaveSnapshotSuccess) Probe.Tell("saved"); else if (message.ToString() == "snap") SaveSnapshot(Events); else return false; @@ -470,8 +457,8 @@ protected override bool ReceiveCommand(object message) protected override void OnPersistFailure(Exception cause, object @event, long sequenceNr) { - if (@event is Evt) - Sender.Tell(string.Format("Failure: {0}", ((Evt)@event).Data)); + if (@event is Evt evt) + Sender.Tell(string.Format("Failure: {0}", evt.Data)); else base.OnPersistFailure(cause, @event, sequenceNr); } @@ -831,16 +818,14 @@ public StressOrdering(string name) protected override bool ReceiveCommand(object message) { - if (message is LatchCmd) + if (message is LatchCmd latchCmd) { - var latchCmd = message as LatchCmd; Sender.Tell(latchCmd.Data); latchCmd.Latch.Ready(TimeSpan.FromSeconds(5)); PersistAsync(latchCmd.Data, _ => { }); } - else if (message is Cmd) + else if (message is Cmd cmd) { - var cmd = message as Cmd; Sender.Tell(cmd.Data); PersistAsync(cmd.Data, _ => { }); } @@ -888,9 +873,8 @@ public MultipleAndNestedPersists(string name, IActorRef probe) protected override bool ReceiveCommand(object message) { - if (message is string) + if (message is string s) { - var s = (string)message; _probe.Tell(s); Persist(s + "-outer-1", outer => { @@ -920,9 +904,8 @@ public MultipleAndNestedPersistAsyncs(string name, IActorRef probe) protected override bool ReceiveCommand(object message) { - if (message is string) + if (message is string s) { - var s = (string)message; _probe.Tell(s); PersistAsync(s + "-outer-1", outer => { @@ -952,9 +935,8 @@ public NestedPersistNormalAndAsyncs(string name, IActorRef probe) protected override bool ReceiveCommand(object message) { - if (message is string) + if (message is string s) { - var s = (string)message; _probe.Tell(s); Persist(s + "-outer-1", outer => { @@ -984,9 +966,8 @@ public NestedPersistAsyncsAndNormal(string name, IActorRef probe) protected override bool ReceiveCommand(object message) { - if (message is string) + if (message is string s) { - var s = (string)message; _probe.Tell(s); PersistAsync(s + "-outer-async-1", outer => { @@ -1016,9 +997,8 @@ public NestedPersistInAsyncEnforcesStashing(string name, IActorRef probe) protected override bool ReceiveCommand(object message) { - if (message is string) + if (message is string s) { - var s = (string)message; _probe.Tell(s); PersistAsync(s + "-outer-async", outer => { @@ -1074,9 +1054,8 @@ private void WeMustGoDeeper(string dWithDepth) protected override bool ReceiveCommand(object message) { - if (message is string) + if (message is string s) { - var s = (string)message; _probe.Tell(s); Persist(s + "-1", WeMustGoDeeper); return true; @@ -1118,9 +1097,8 @@ private void WeMustGoDeeper(string dWithDepth) protected override bool ReceiveCommand(object message) { - if (message is string) + if (message is string s) { - var s = (string)message; _probe.Tell(s); PersistAsync(s + "-1", WeMustGoDeeper); return true; diff --git a/src/core/Akka.Persistence.Tests/PersistentActorSpecAsyncAwait.Actors.cs b/src/core/Akka.Persistence.Tests/PersistentActorSpecAsyncAwait.Actors.cs index f587f3ff5f4..42a5ca742b3 100644 --- a/src/core/Akka.Persistence.Tests/PersistentActorSpecAsyncAwait.Actors.cs +++ b/src/core/Akka.Persistence.Tests/PersistentActorSpecAsyncAwait.Actors.cs @@ -52,16 +52,16 @@ protected bool Receiver(object message) protected override void OnPersistRejected(Exception cause, object @event, long sequenceNr) { - if (@event is Evt) - Sender.Tell("Rejected: " + ((Evt)@event).Data); + if (@event is Evt evt) + Sender.Tell("Rejected: " + evt.Data); else base.OnPersistRejected(cause, @event, sequenceNr); } protected override void OnPersistFailure(Exception cause, object @event, long sequenceNr) { - if (@event is Evt) - Sender.Tell("Failure: " + ((Evt)@event).Data); + if (@event is Evt evt) + Sender.Tell("Failure: " + evt.Data); else base.OnPersistFailure(cause, @event, sequenceNr); } @@ -148,10 +148,10 @@ protected override bool ReceiveRecover(object message) protected bool UpdateState(object message) { - if (message is Evt) - Events = Events.AddFirst((message as Evt).Data); - else if (message is IActorRef) - AskedForDelete = (IActorRef)message; + if (message is Evt evt) + Events = Events.AddFirst(evt.Data); + else if (message is IActorRef @ref) + AskedForDelete = @ref; else return false; return true; @@ -412,10 +412,10 @@ protected override bool ReceiveRecover(object message) { if (!base.ReceiveRecover(message)) { - if (message is SnapshotOffer) + if (message is SnapshotOffer offer) { Probe.Tell("offered"); - Events = (message as SnapshotOffer).Snapshot.AsInstanceOf>(); + Events = offer.Snapshot.AsInstanceOf>(); } else return false; } @@ -425,7 +425,7 @@ protected override bool ReceiveRecover(object message) protected override bool ReceiveCommand(object message) { if (CommonBehavior(message)) return true; - if (message is Cmd) HandleCmd(message as Cmd); + if (message is Cmd cmd) HandleCmd(cmd); else if (message is SaveSnapshotSuccess) Probe.Tell("saved"); else if (message.ToString() == "snap") SaveSnapshot(Events); else return false; @@ -532,8 +532,8 @@ protected override bool ReceiveCommand(object message) protected override void OnPersistFailure(Exception cause, object @event, long sequenceNr) { - if (@event is Evt) - Sender.Tell(string.Format("Failure: {0}", ((Evt)@event).Data)); + if (@event is Evt evt) + Sender.Tell(string.Format("Failure: {0}", evt.Data)); else base.OnPersistFailure(cause, @event, sequenceNr); } diff --git a/src/core/Akka.Persistence.Tests/PersistentActorStashingSpec.cs b/src/core/Akka.Persistence.Tests/PersistentActorStashingSpec.cs index e368ad12196..a9384d1d371 100644 --- a/src/core/Akka.Persistence.Tests/PersistentActorStashingSpec.cs +++ b/src/core/Akka.Persistence.Tests/PersistentActorStashingSpec.cs @@ -36,9 +36,8 @@ protected override bool ReceiveCommand(object message) { if (!UnstashBehavior(message)) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; if (cmd.Data.ToString() == "a") { if (!_stashed) @@ -64,9 +63,8 @@ protected override bool ReceiveCommand(object message) protected override bool UnstashBehavior(object message) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; if (cmd.Data.ToString() == "c") { Stash.UnstashAll(); @@ -87,9 +85,8 @@ public UserStashWithinHandlerActor(string name) : base(name) protected override bool UnstashBehavior(object message) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = message as Cmd; if (cmd.Data.ToString() == "c") { Persist(new Evt("c"), e => @@ -377,9 +374,9 @@ protected override bool ReceiveCommand(object message) { if (!CommonBehavior(message) && !UnstashBehavior(message)) { - if (message is Cmd) + if (message is Cmd cmd) { - var data = ((Cmd) message).Data; + var data = cmd.Data; if (data.Equals("a")) { PersistAsync(new Evt("a"), UpdateStateHandler); diff --git a/src/core/Akka.Persistence.Tests/Serialization/MessageSerializerRemotingSpec.cs b/src/core/Akka.Persistence.Tests/Serialization/MessageSerializerRemotingSpec.cs index e8442ad3413..340dcd5bbb7 100644 --- a/src/core/Akka.Persistence.Tests/Serialization/MessageSerializerRemotingSpec.cs +++ b/src/core/Akka.Persistence.Tests/Serialization/MessageSerializerRemotingSpec.cs @@ -120,19 +120,17 @@ internal class RemoteActor : ActorBase { protected override bool Receive(object message) { - if (message is Persistent) + if (message is Persistent persistent) { - var p = (Persistent) message; - if (p.Payload is MyPayload) + if (persistent.Payload is MyPayload) { - p.Sender.Tell("p" + ((MyPayload) p.Payload).Data); + persistent.Sender.Tell("p" + ((MyPayload) persistent.Payload).Data); } else return false; } - else if (message is AtomicWrite) + else if (message is AtomicWrite write) { - var a = (AtomicWrite) message; - foreach (var p in (IEnumerable) a.Payload) + foreach (var p in (IEnumerable) write.Payload) { if (p.Payload is MyPayload) { diff --git a/src/core/Akka.Persistence.Tests/Serialization/TestSerializers.cs b/src/core/Akka.Persistence.Tests/Serialization/TestSerializers.cs index 4e72119f7d8..33781584181 100644 --- a/src/core/Akka.Persistence.Tests/Serialization/TestSerializers.cs +++ b/src/core/Akka.Persistence.Tests/Serialization/TestSerializers.cs @@ -31,8 +31,8 @@ public override bool IncludeManifest public override byte[] ToBinary(object obj) { - if (obj is MyPayload) - return Encoding.UTF8.GetBytes("." + ((MyPayload) obj).Data); + if (obj is MyPayload payload) + return Encoding.UTF8.GetBytes("." + payload.Data); return null; } diff --git a/src/core/Akka.Persistence.Tests/SnapshotDirectoryFailureSpec.cs b/src/core/Akka.Persistence.Tests/SnapshotDirectoryFailureSpec.cs index 2fbecaa4ba9..ec97f2d3c3b 100644 --- a/src/core/Akka.Persistence.Tests/SnapshotDirectoryFailureSpec.cs +++ b/src/core/Akka.Persistence.Tests/SnapshotDirectoryFailureSpec.cs @@ -41,8 +41,8 @@ protected override bool ReceiveCommand(object message) { if (message is string) SaveSnapshot(message); - else if (message is SaveSnapshotSuccess) - _probe.Tell(((SaveSnapshotSuccess)message).Metadata.SequenceNr); + else if (message is SaveSnapshotSuccess success) + _probe.Tell(success.Metadata.SequenceNr); else _probe.Tell(message); return true; diff --git a/src/core/Akka.Persistence.Tests/SnapshotFailureRobustnessSpec.cs b/src/core/Akka.Persistence.Tests/SnapshotFailureRobustnessSpec.cs index ef63ea8ab4a..96a489bd5ae 100644 --- a/src/core/Akka.Persistence.Tests/SnapshotFailureRobustnessSpec.cs +++ b/src/core/Akka.Persistence.Tests/SnapshotFailureRobustnessSpec.cs @@ -100,17 +100,16 @@ protected override bool ReceiveRecover(object message) protected override bool ReceiveCommand(object message) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = (Cmd) message; Persist(cmd.Payload, _ => SaveSnapshot(cmd.Payload)); } - else if (message is DeleteSnapshot) - DeleteSnapshot(((DeleteSnapshot)message).SequenceNr); - else if (message is DeleteSnapshots) - DeleteSnapshots(((DeleteSnapshots)message).Criteria); - else if (message is SaveSnapshotSuccess) - _probe.Tell(((SaveSnapshotSuccess)message).Metadata.SequenceNr); + else if (message is DeleteSnapshot snapshot) + DeleteSnapshot(snapshot.SequenceNr); + else if (message is DeleteSnapshots snapshots) + DeleteSnapshots(snapshots.Criteria); + else if (message is SaveSnapshotSuccess success) + _probe.Tell(success.Metadata.SequenceNr); else _probe.Tell(message); return true; @@ -137,17 +136,16 @@ protected override bool ReceiveRecover(object message) protected override bool ReceiveCommand(object message) { - if (message is Cmd) + if (message is Cmd cmd) { - var cmd = (Cmd) message; Persist(cmd.Payload, _ => SaveSnapshot(cmd.Payload)); } - else if (message is DeleteSnapshot) - DeleteSnapshot(((DeleteSnapshot)message).SequenceNr); - else if (message is DeleteSnapshots) - DeleteSnapshots(((DeleteSnapshots)message).Criteria); - else if (message is SaveSnapshotSuccess) - _probe.Tell(((SaveSnapshotSuccess)message).Metadata.SequenceNr); + else if (message is DeleteSnapshot snapshot) + DeleteSnapshot(snapshot.SequenceNr); + else if (message is DeleteSnapshots snapshots) + DeleteSnapshots(snapshots.Criteria); + else if (message is SaveSnapshotSuccess success) + _probe.Tell(success.Metadata.SequenceNr); else _probe.Tell(message); return true; diff --git a/src/core/Akka.Persistence.Tests/SnapshotRecoveryLocalStoreSpec.cs b/src/core/Akka.Persistence.Tests/SnapshotRecoveryLocalStoreSpec.cs index 73cb24f6ef1..d7d0451f0f4 100644 --- a/src/core/Akka.Persistence.Tests/SnapshotRecoveryLocalStoreSpec.cs +++ b/src/core/Akka.Persistence.Tests/SnapshotRecoveryLocalStoreSpec.cs @@ -42,8 +42,8 @@ protected override bool ReceiveCommand(object message) { if (message is TakeSnapshot) SaveSnapshot(_state); - else if (message is SaveSnapshotSuccess) - _probe.Tell(((SaveSnapshotSuccess)message).Metadata.SequenceNr); + else if (message is SaveSnapshotSuccess success) + _probe.Tell(success.Metadata.SequenceNr); else if (message is GetState) _probe.Tell(_state); else return false; diff --git a/src/core/Akka.Persistence.Tests/SnapshotSerializationSpec.cs b/src/core/Akka.Persistence.Tests/SnapshotSerializationSpec.cs index a66f583d7cb..cc12eb658dc 100644 --- a/src/core/Akka.Persistence.Tests/SnapshotSerializationSpec.cs +++ b/src/core/Akka.Persistence.Tests/SnapshotSerializationSpec.cs @@ -75,10 +75,8 @@ public override byte[] ToBinary(object obj) { var msg = obj is - SnapshotTypeWithAFullyQualifiedNameLongerThan255BytesXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - ? (( - SnapshotTypeWithAFullyQualifiedNameLongerThan255BytesXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - ) obj).Id + SnapshotTypeWithAFullyQualifiedNameLongerThan255BytesXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + ? xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.Id : "unknown"; writer.Write(msg); writer.Flush(); @@ -122,11 +120,11 @@ protected override bool ReceiveRecover(object message) protected override bool ReceiveCommand(object message) { - if (message is string) + if (message is string s) SaveSnapshot(new SnapshotTypeWithAFullyQualifiedNameLongerThan255BytesXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( - (string)message)); - else if (message is SaveSnapshotSuccess) - _probe.Tell(((SaveSnapshotSuccess)message).Metadata.SequenceNr); + s)); + else if (message is SaveSnapshotSuccess success) + _probe.Tell(success.Metadata.SequenceNr); else _probe.Tell(message); return true; diff --git a/src/core/Akka.Persistence/Journal/AsyncWriteProxy.cs b/src/core/Akka.Persistence/Journal/AsyncWriteProxy.cs index b3d9a0d1935..1d20eb81b95 100644 --- a/src/core/Akka.Persistence/Journal/AsyncWriteProxy.cs +++ b/src/core/Akka.Persistence/Journal/AsyncWriteProxy.cs @@ -465,15 +465,14 @@ public ReplayMediator(Action replayCallback, TaskComp /// TBD protected override bool Receive(object message) { - if (message is IPersistentRepresentation) _replayCallback(message as IPersistentRepresentation); + if (message is IPersistentRepresentation representation) _replayCallback(representation); else if (message is AsyncWriteTarget.ReplaySuccess) { _replayCompletionPromise.SetResult(new object()); Context.Stop(Self); } - else if (message is AsyncWriteTarget.ReplayFailure) + else if (message is AsyncWriteTarget.ReplayFailure failure) { - var failure = message as AsyncWriteTarget.ReplayFailure; _replayCompletionPromise.SetException(failure.Cause); Context.Stop(Self); } diff --git a/src/core/Akka.Persistence/Journal/PersistencePluginProxy.cs b/src/core/Akka.Persistence/Journal/PersistencePluginProxy.cs index d5892320796..9585f803a41 100644 --- a/src/core/Akka.Persistence/Journal/PersistencePluginProxy.cs +++ b/src/core/Akka.Persistence/Journal/PersistencePluginProxy.cs @@ -192,10 +192,10 @@ protected override bool Receive(object message) private bool Init(object message) { - if (message is TargetLocation) + if (message is TargetLocation location) { Context.SetReceiveTimeout(TimeSpan.FromSeconds(1)); // for retries - Context.Become(Identifying(((TargetLocation)message).Address)); + Context.Become(Identifying(location.Address)); } else if (message is InitTimeout) { @@ -233,9 +233,8 @@ private Receive Identifying(Address address) { return message => { - if (message is ActorIdentity) + if (message is ActorIdentity ai) { - var ai = (ActorIdentity)message; if (_targetPluginId.Equals(ai.MessageId)) { var target = ai.Subject; @@ -265,16 +264,15 @@ private Receive Active(IActorRef targetJournal, bool targetAtThisNode) { return message => { - if (message is TargetLocation) + if (message is TargetLocation location) { - var address = ((TargetLocation)message).Address; + var address = location.Address; if (targetAtThisNode && !address.Equals(_selfAddress)) BecomeIdentifying(address); } - else if (message is Terminated) + else if (message is Terminated terminated) { - var t = (Terminated)message; - if (t.ActorRef.Equals(targetJournal)) + if (terminated.ActorRef.Equals(targetJournal)) { Context.Unwatch(targetJournal); Context.Become(InitTimedOut()); @@ -316,44 +314,38 @@ private Receive InitTimedOut() } } } - else if (message is ReplayMessages) + else if (message is ReplayMessages messages) { - var r = (ReplayMessages)message; - r.PersistentActor.Tell(new ReplayMessagesFailure(TimeoutException())); + messages.PersistentActor.Tell(new ReplayMessagesFailure(TimeoutException())); } - else if (message is DeleteMessagesTo) + else if (message is DeleteMessagesTo to) { - var d = (DeleteMessagesTo)message; - d.PersistentActor.Tell(new DeleteMessagesFailure(TimeoutException(), d.ToSequenceNr)); + to.PersistentActor.Tell(new DeleteMessagesFailure(TimeoutException(), to.ToSequenceNr)); } } else if (message is ISnapshotRequest) { // exhaustive match - if (message is LoadSnapshot) + if (message is LoadSnapshot snapshot) { - var l = (LoadSnapshot)message; Sender.Tell(new LoadSnapshotFailed(TimeoutException())); } - else if (message is SaveSnapshot) + else if (message is SaveSnapshot saveSnapshot) { - var s = (SaveSnapshot)message; - Sender.Tell(new SaveSnapshotFailure(s.Metadata, TimeoutException())); + Sender.Tell(new SaveSnapshotFailure(saveSnapshot.Metadata, TimeoutException())); } - else if (message is DeleteSnapshot) + else if (message is DeleteSnapshot deleteSnapshot) { - var d = (DeleteSnapshot)message; - Sender.Tell(new DeleteSnapshotFailure(d.Metadata, TimeoutException())); + Sender.Tell(new DeleteSnapshotFailure(deleteSnapshot.Metadata, TimeoutException())); } - else if (message is DeleteSnapshots) + else if (message is DeleteSnapshots snapshots) { - var d = (DeleteSnapshots)message; - Sender.Tell(new DeleteSnapshotsFailure(d.Criteria, TimeoutException())); + Sender.Tell(new DeleteSnapshotsFailure(snapshots.Criteria, TimeoutException())); } } - else if (message is TargetLocation) + else if (message is TargetLocation location) { - BecomeIdentifying(((TargetLocation)message).Address); + BecomeIdentifying(location.Address); } else if (message is Terminated) { diff --git a/src/core/Akka.Persistence/Journal/ReplayFilter.cs b/src/core/Akka.Persistence/Journal/ReplayFilter.cs index 4b9304f42fe..7f4247cd732 100644 --- a/src/core/Akka.Persistence/Journal/ReplayFilter.cs +++ b/src/core/Akka.Persistence/Journal/ReplayFilter.cs @@ -131,11 +131,10 @@ public static Props Props(IActorRef persistentActor, ReplayFilterMode mode, int /// TBD protected override bool Receive(object message) { - if (message is ReplayedMessage) + if (message is ReplayedMessage value) { - var r = (ReplayedMessage) message; if (DebugEnabled && _log.IsDebugEnabled) - _log.Debug($"Replay: {r.Persistent}"); + _log.Debug($"Replay: {value.Persistent}"); try { @@ -146,13 +145,13 @@ protected override bool Receive(object message) PersistentActor.Tell(msg.Value, ActorRefs.NoSender); } - if (r.Persistent.WriterGuid.Equals(_writerUuid)) + if (value.Persistent.WriterGuid.Equals(_writerUuid)) { // from same writer - if (r.Persistent.SequenceNr < _sequenceNr) + if (value.Persistent.SequenceNr < _sequenceNr) { - var errMsg = $@"Invalid replayed event [sequenceNr={r.Persistent.SequenceNr}, writerUUID={r.Persistent.WriterGuid}] as - the sequenceNr should be equal to or greater than already-processed event [sequenceNr={_sequenceNr}, writerUUID={_writerUuid}] from the same writer, for the same persistenceId [{r.Persistent.PersistenceId}]. + var errMsg = $@"Invalid replayed event [sequenceNr={value.Persistent.SequenceNr}, writerUUID={value.Persistent.WriterGuid}] as + the sequenceNr should be equal to or greater than already-processed event [sequenceNr={_sequenceNr}, writerUUID={_writerUuid}] from the same writer, for the same persistenceId [{value.Persistent.PersistenceId}]. Perhaps, events were journaled out of sequence, or duplicate PersistentId for different entities?"; LogIssue(errMsg); switch (Mode) @@ -163,7 +162,7 @@ protected override bool Receive(object message) case ReplayFilterMode.Fail: throw new IllegalStateException(errMsg); case ReplayFilterMode.Warn: - _buffer.AddLast(r); + _buffer.AddLast(value); break; case ReplayFilterMode.Disabled: throw new ArgumentException("Mode must not be Disabled"); @@ -172,15 +171,15 @@ protected override bool Receive(object message) else { // note that it is alright with == _sequenceNr, since such may be emitted by EventSeq - _buffer.AddLast(r); - _sequenceNr = r.Persistent.SequenceNr; + _buffer.AddLast(value); + _sequenceNr = value.Persistent.SequenceNr; } } - else if (_oldWriters.Contains(r.Persistent.WriterGuid)) + else if (_oldWriters.Contains(value.Persistent.WriterGuid)) { // from old writer - var errMsg = $@"Invalid replayed event [sequenceNr={r.Persistent.SequenceNr}, writerUUID={r.Persistent.WriterGuid}]. - There was already a newer writer whose last replayed event was [sequenceNr={_sequenceNr}, writerUUID={_writerUuid}] for the same persistenceId [{r.Persistent.PersistenceId}]. + var errMsg = $@"Invalid replayed event [sequenceNr={value.Persistent.SequenceNr}, writerUUID={value.Persistent.WriterGuid}]. + There was already a newer writer whose last replayed event was [sequenceNr={_sequenceNr}, writerUUID={_writerUuid}] for the same persistenceId [{value.Persistent.PersistenceId}]. Perhaps, the old writer kept journaling messages after the new writer created, or duplicate PersistentId for different entities?"; LogIssue(errMsg); switch (Mode) @@ -191,7 +190,7 @@ protected override bool Receive(object message) case ReplayFilterMode.Fail: throw new IllegalStateException(errMsg); case ReplayFilterMode.Warn: - _buffer.AddLast(r); + _buffer.AddLast(value); break; case ReplayFilterMode.Disabled: throw new ArgumentException("Mode must not be Disabled"); @@ -204,8 +203,8 @@ protected override bool Receive(object message) _oldWriters.AddLast(_writerUuid); if (_oldWriters.Count > MaxOldWriters) _oldWriters.RemoveFirst(); - _writerUuid = r.Persistent.WriterGuid; - _sequenceNr = r.Persistent.SequenceNr; + _writerUuid = value.Persistent.WriterGuid; + _sequenceNr = value.Persistent.SequenceNr; // clear the buffer from messages from other writers with higher SequenceNr var node = _buffer.First; @@ -215,8 +214,8 @@ protected override bool Receive(object message) var msg = node.Value; if (msg.Persistent.SequenceNr >= _sequenceNr) { - var errMsg = $@"Invalid replayed event [sequenceNr=${r.Persistent.SequenceNr}, writerUUID=${r.Persistent.WriterGuid}] from a new writer. - An older writer already sent an event [sequenceNr=${msg.Persistent.SequenceNr}, writerUUID=${msg.Persistent.WriterGuid}] whose sequence number was equal or greater for the same persistenceId [${r.Persistent.PersistenceId}]. + var errMsg = $@"Invalid replayed event [sequenceNr=${value.Persistent.SequenceNr}, writerUUID=${value.Persistent.WriterGuid}] from a new writer. + An older writer already sent an event [sequenceNr=${msg.Persistent.SequenceNr}, writerUUID=${msg.Persistent.WriterGuid}] whose sequence number was equal or greater for the same persistenceId [${value.Persistent.PersistenceId}]. Perhaps, the new writer journaled the event out of sequence, or duplicate PersistentId for different entities?"; LogIssue(errMsg); switch (Mode) @@ -236,7 +235,7 @@ protected override bool Receive(object message) } node = next; } - _buffer.AddLast(r); + _buffer.AddLast(value); } } diff --git a/src/core/Akka.Persistence/Persistent.cs b/src/core/Akka.Persistence/Persistent.cs index 4ab4da62444..d92f341fdfd 100644 --- a/src/core/Akka.Persistence/Persistent.cs +++ b/src/core/Akka.Persistence/Persistent.cs @@ -183,7 +183,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is AtomicWrite && Equals((AtomicWrite)obj); + return obj is AtomicWrite write && Equals(write); } diff --git a/src/core/Akka.Persistence/Serialization/Snapshot.cs b/src/core/Akka.Persistence/Serialization/Snapshot.cs index 666b41ef467..8cb852f98b2 100644 --- a/src/core/Akka.Persistence/Serialization/Snapshot.cs +++ b/src/core/Akka.Persistence/Serialization/Snapshot.cs @@ -44,7 +44,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Snapshot && Equals((Snapshot)obj); + return obj is Snapshot snapshot && Equals(snapshot); } diff --git a/src/core/Akka.Persistence/SnapshotProtocol.cs b/src/core/Akka.Persistence/SnapshotProtocol.cs index 74fde29079f..88ba802d139 100644 --- a/src/core/Akka.Persistence/SnapshotProtocol.cs +++ b/src/core/Akka.Persistence/SnapshotProtocol.cs @@ -767,7 +767,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is LoadSnapshotFailed && Equals((LoadSnapshotFailed)obj); + return obj is LoadSnapshotFailed failed && Equals(failed); } public override int GetHashCode() => Cause?.GetHashCode() ?? 0; diff --git a/src/core/Akka.Remote.TestKit.Tests/BarrierSpec.cs b/src/core/Akka.Remote.TestKit.Tests/BarrierSpec.cs index 60c5a01f75f..67ea5977a83 100644 --- a/src/core/Akka.Remote.TestKit.Tests/BarrierSpec.cs +++ b/src/core/Akka.Remote.TestKit.Tests/BarrierSpec.cs @@ -45,7 +45,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Failed && Equals((Failed) obj); + return obj is Failed failed && Equals(failed); } public override int GetHashCode() diff --git a/src/core/Akka.Remote.TestKit/BarrierCoordinator.cs b/src/core/Akka.Remote.TestKit/BarrierCoordinator.cs index 68c91f92b35..a0ae256eb2d 100644 --- a/src/core/Akka.Remote.TestKit/BarrierCoordinator.cs +++ b/src/core/Akka.Remote.TestKit/BarrierCoordinator.cs @@ -96,7 +96,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Data && Equals((Data) obj); + return obj is Data data && Equals(data); } /// @@ -155,7 +155,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is BarrierTimeoutException && Equals((BarrierTimeoutException) obj); + return obj is BarrierTimeoutException exception && Equals(exception); } /// @@ -207,7 +207,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is FailedBarrierException && Equals((FailedBarrierException) obj); + return obj is FailedBarrierException exception && Equals(exception); } /// @@ -262,7 +262,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is DuplicateNodeException && Equals((DuplicateNodeException) obj); + return obj is DuplicateNodeException exception && Equals(exception); } /// @@ -323,7 +323,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is WrongBarrierException && Equals((WrongBarrierException) obj); + return obj is WrongBarrierException exception && Equals(exception); } /// @@ -381,7 +381,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is BarrierEmptyException && Equals((BarrierEmptyException) obj); + return obj is BarrierEmptyException exception && Equals(exception); } /// @@ -436,7 +436,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is ClientLostException && Equals((ClientLostException) obj); + return obj is ClientLostException exception && Equals(exception); } /// diff --git a/src/core/Akka.Remote.TestKit/Controller.cs b/src/core/Akka.Remote.TestKit/Controller.cs index 9e717d3094f..579fa216d7d 100644 --- a/src/core/Akka.Remote.TestKit/Controller.cs +++ b/src/core/Akka.Remote.TestKit/Controller.cs @@ -49,7 +49,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is ClientDisconnected && Equals((ClientDisconnected) obj); + return obj is ClientDisconnected disconnected && Equals(disconnected); } /// diff --git a/src/core/Akka.Remote.TestKit/DataTypes.cs b/src/core/Akka.Remote.TestKit/DataTypes.cs index 8676d8e6446..3b5b51bb7c5 100644 --- a/src/core/Akka.Remote.TestKit/DataTypes.cs +++ b/src/core/Akka.Remote.TestKit/DataTypes.cs @@ -241,7 +241,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Hello && Equals((Hello)obj); + return obj is Hello hello && Equals(hello); } @@ -313,7 +313,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is EnterBarrier && Equals((EnterBarrier)obj); + return obj is EnterBarrier barrier && Equals(barrier); } @@ -382,7 +382,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is FailBarrier && Equals((FailBarrier)obj); + return obj is FailBarrier barrier && Equals(barrier); } @@ -445,7 +445,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is BarrierResult && Equals((BarrierResult)obj); + return obj is BarrierResult result && Equals(result); } @@ -525,7 +525,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Throttle && Equals((Throttle)obj); + return obj is Throttle throttle && Equals(throttle); } @@ -602,7 +602,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is ThrottleMsg && Equals((ThrottleMsg)obj); + return obj is ThrottleMsg msg && Equals(msg); } @@ -678,7 +678,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Disconnect && Equals((Disconnect)obj); + return obj is Disconnect disconnect && Equals(disconnect); } @@ -747,7 +747,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is DisconnectMsg && Equals((DisconnectMsg)obj); + return obj is DisconnectMsg msg && Equals(msg); } @@ -813,7 +813,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Terminate && Equals((Terminate)obj); + return obj is Terminate terminate && Equals(terminate); } @@ -872,7 +872,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is TerminateMsg && Equals((TerminateMsg)obj); + return obj is TerminateMsg msg && Equals(msg); } @@ -928,7 +928,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is GetAddress && Equals((GetAddress)obj); + return obj is GetAddress address && Equals(address); } @@ -991,7 +991,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is AddressReply && Equals((AddressReply)obj); + return obj is AddressReply reply && Equals(reply); } @@ -1064,7 +1064,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Remove && Equals((Remove)obj); + return obj is Remove remove && Equals(remove); } diff --git a/src/core/Akka.Remote.TestKit/MsgEncoder.cs b/src/core/Akka.Remote.TestKit/MsgEncoder.cs index 9566cd93850..8e633a74107 100644 --- a/src/core/Akka.Remote.TestKit/MsgEncoder.cs +++ b/src/core/Akka.Remote.TestKit/MsgEncoder.cs @@ -48,18 +48,16 @@ protected override void Encode(IChannelHandlerContext context, object message, L var wrapper = new Proto.Msg.Wrapper(); - if (message is Hello) + if (message is Hello hello) { - var hello = (Hello)message; wrapper.Hello = new Proto.Msg.Hello { Name = hello.Name, Address = AddressMessageBuilder(hello.Address) }; } - else if (message is EnterBarrier) + else if (message is EnterBarrier enterBarrier) { - var enterBarrier = (EnterBarrier)message; wrapper.Barrier = new Proto.Msg.EnterBarrier { Name = enterBarrier.Name, @@ -67,9 +65,8 @@ protected override void Encode(IChannelHandlerContext context, object message, L Op = Proto.Msg.EnterBarrier.Types.BarrierOp.Enter, }; } - else if (message is BarrierResult) + else if (message is BarrierResult barrierResult) { - var barrierResult = (BarrierResult)message; wrapper.Barrier = new Proto.Msg.EnterBarrier { Name = barrierResult.Name, @@ -78,18 +75,16 @@ protected override void Encode(IChannelHandlerContext context, object message, L : Proto.Msg.EnterBarrier.Types.BarrierOp.Failed }; } - else if (message is FailBarrier) + else if (message is FailBarrier failBarrier) { - var failBarrier = (FailBarrier)message; wrapper.Barrier = new Proto.Msg.EnterBarrier { Name = failBarrier.Name, Op = Proto.Msg.EnterBarrier.Types.BarrierOp.Fail }; } - else if (message is ThrottleMsg) + else if (message is ThrottleMsg throttleMsg) { - var throttleMsg = (ThrottleMsg)message; wrapper.Failure = new Proto.Msg.InjectFailure { Address = AddressMessageBuilder(throttleMsg.Target), @@ -98,9 +93,8 @@ protected override void Encode(IChannelHandlerContext context, object message, L RateMBit = throttleMsg.RateMBit }; } - else if (message is DisconnectMsg) + else if (message is DisconnectMsg disconnectMsg) { - var disconnectMsg = (DisconnectMsg)message; wrapper.Failure = new Proto.Msg.InjectFailure { Address = AddressMessageBuilder(disconnectMsg.Target), @@ -109,9 +103,8 @@ protected override void Encode(IChannelHandlerContext context, object message, L : Proto.Msg.InjectFailure.Types.FailType.Disconnect }; } - else if (message is TerminateMsg) + else if (message is TerminateMsg terminate) { - var terminate = (TerminateMsg)message; if (terminate.ShutdownOrExit.IsRight) { wrapper.Failure = new Proto.Msg.InjectFailure() @@ -135,14 +128,12 @@ protected override void Encode(IChannelHandlerContext context, object message, L }; } } - else if (message is GetAddress) + else if (message is GetAddress getAddress) { - var getAddress = (GetAddress)message; wrapper.Addr = new Proto.Msg.AddressRequest { Node = getAddress.Node.Name }; } - else if (message is AddressReply) + else if (message is AddressReply addressReply) { - var addressReply = (AddressReply)message; wrapper.Addr = new Proto.Msg.AddressRequest { Node = addressReply.Node.Name, diff --git a/src/core/Akka.Remote/AckedDelivery.cs b/src/core/Akka.Remote/AckedDelivery.cs index aa113b9c658..f884e80f94c 100644 --- a/src/core/Akka.Remote/AckedDelivery.cs +++ b/src/core/Akka.Remote/AckedDelivery.cs @@ -171,7 +171,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is SeqNo && Equals((SeqNo) obj); + return obj is SeqNo no && Equals(no); } /// diff --git a/src/core/Akka.Remote/RemoteSystemDaemon.cs b/src/core/Akka.Remote/RemoteSystemDaemon.cs index 9ca2a786ab1..7e75b1b2493 100644 --- a/src/core/Akka.Remote/RemoteSystemDaemon.cs +++ b/src/core/Akka.Remote/RemoteSystemDaemon.cs @@ -123,7 +123,7 @@ protected override void TellInternal(object message, IActorRef sender) if (message is IDaemonMsg) { Log.Debug("Received command [{0}] to RemoteSystemDaemon on [{1}]", message, Path.Address); - if (message is DaemonMsgCreate) HandleDaemonMsgCreate((DaemonMsgCreate)message); + if (message is DaemonMsgCreate create) HandleDaemonMsgCreate(create); } else if (message is ActorSelectionMessage sel) { @@ -172,9 +172,8 @@ protected override void TellInternal(object message, IActorRef sender) } //Remote ActorSystem on another process / machine has died. //Need to clean up any references to remote deployments here. - else if (message is AddressTerminated) + else if (message is AddressTerminated addressTerminated) { - var addressTerminated = (AddressTerminated)message; //stop any remote actors that belong to this address ForEachChild(@ref => { diff --git a/src/core/Akka.Remote/Serialization/SystemMessageSerializer.cs b/src/core/Akka.Remote/Serialization/SystemMessageSerializer.cs index f4a20235117..43a97913684 100644 --- a/src/core/Akka.Remote/Serialization/SystemMessageSerializer.cs +++ b/src/core/Akka.Remote/Serialization/SystemMessageSerializer.cs @@ -39,16 +39,16 @@ public SystemMessageSerializer(ExtendedActorSystem system) : base(system) /// public override byte[] ToBinary(object obj) { - if (obj is Create) return CreateToProto((Create)obj); - if (obj is Recreate) return RecreateToProto((Recreate)obj); + if (obj is Create create) return CreateToProto(create); + if (obj is Recreate recreate) return RecreateToProto(recreate); if (obj is Suspend) return EmptyBytes; - if (obj is Resume) return ResumeToProto((Resume)obj); + if (obj is Resume resume) return ResumeToProto(resume); if (obj is Terminate) return EmptyBytes; - if (obj is Supervise) return SuperviseToProto((Supervise)obj); - if (obj is Watch) return WatchToProto((Watch)obj); - if (obj is Unwatch) return UnwatchToProto((Unwatch)obj); - if (obj is Failed) return FailedToProto((Failed)obj); - if (obj is DeathWatchNotification) return DeathWatchNotificationToProto((DeathWatchNotification)obj); + if (obj is Supervise supervise) return SuperviseToProto(supervise); + if (obj is Watch watch) return WatchToProto(watch); + if (obj is Unwatch unwatch) return UnwatchToProto(unwatch); + if (obj is Failed failed) return FailedToProto(failed); + if (obj is DeathWatchNotification notification) return DeathWatchNotificationToProto(notification); if (obj is NoMessage) throw new ArgumentException("NoMessage should never be serialized or deserialized"); throw new ArgumentException($"Cannot serialize object of type [{obj.GetType().TypeQualifiedName()}]"); diff --git a/src/core/Akka.Remote/Transport/AkkaProtocolTransport.cs b/src/core/Akka.Remote/Transport/AkkaProtocolTransport.cs index a6d9350c2ab..53274a2e12a 100644 --- a/src/core/Akka.Remote/Transport/AkkaProtocolTransport.cs +++ b/src/core/Akka.Remote/Transport/AkkaProtocolTransport.cs @@ -354,7 +354,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is HandshakeInfo && Equals((HandshakeInfo)obj); + return obj is HandshakeInfo info && Equals(info); } private bool Equals(HandshakeInfo other) diff --git a/src/core/Akka.Remote/Transport/DotNetty/AkkaLoggingHandler.cs b/src/core/Akka.Remote/Transport/DotNetty/AkkaLoggingHandler.cs index 0c37a30ef1f..8e536e5fd8e 100644 --- a/src/core/Akka.Remote/Transport/DotNetty/AkkaLoggingHandler.cs +++ b/src/core/Akka.Remote/Transport/DotNetty/AkkaLoggingHandler.cs @@ -139,13 +139,13 @@ protected string Format(IChannelHandlerContext ctx, string eventName) protected string Format(IChannelHandlerContext ctx, string eventName, object arg) { - if (arg is IByteBuffer) + if (arg is IByteBuffer buffer) { - return this.FormatByteBuffer(ctx, eventName, (IByteBuffer)arg); + return this.FormatByteBuffer(ctx, eventName, buffer); } - else if (arg is IByteBufferHolder) + else if (arg is IByteBufferHolder holder) { - return this.FormatByteBufferHolder(ctx, eventName, (IByteBufferHolder)arg); + return this.FormatByteBufferHolder(ctx, eventName, holder); } else { diff --git a/src/core/Akka.Remote/Transport/FailureInjectorTransportAdapter.cs b/src/core/Akka.Remote/Transport/FailureInjectorTransportAdapter.cs index 04720c21ff5..24b6c95aa43 100644 --- a/src/core/Akka.Remote/Transport/FailureInjectorTransportAdapter.cs +++ b/src/core/Akka.Remote/Transport/FailureInjectorTransportAdapter.cs @@ -232,16 +232,14 @@ protected override SchemeAugmenter SchemeAugmenter /// TBD public override Task ManagementCommand(object message) { - if (message is All) + if (message is All all) { - var all = message as All; _allMode = all.Mode; return Task.FromResult(true); } - if (message is One) + if (message is One one) { - var one = message as One; // don't care about the protocol part - we are injected in the stack anyway! addressChaosTable.AddOrUpdate(NakedAddress(one.RemoteAddress), address => one.Mode, (address, mode) => one.Mode); return Task.FromResult(true); @@ -337,9 +335,8 @@ public bool ShouldDropInbound(Address remoteAddress, object instance, string deb { var mode = ChaosMode(remoteAddress); if (mode is PassThru) return false; - if (mode is Drop) + if (mode is Drop drop) { - var drop = mode as Drop; if (Rng.NextDouble() <= drop.InboundDropP) { if (_shouldDebugLog) _log.Debug("Dropping inbound [{0}] for [{1}] {2}", instance.GetType(), @@ -362,9 +359,8 @@ public bool ShouldDropOutbound(Address remoteAddress, object instance, string de { var mode = ChaosMode(remoteAddress); if (mode is PassThru) return false; - if (mode is Drop) + if (mode is Drop drop) { - var drop = mode as Drop; if (Rng.NextDouble() <= drop.OutboundDropP) { if (_shouldDebugLog) diff --git a/src/core/Akka.Remote/Transport/ThrottleTransportAdapter.cs b/src/core/Akka.Remote/Transport/ThrottleTransportAdapter.cs index 6ce079b7cef..5e8648d2a17 100644 --- a/src/core/Akka.Remote/Transport/ThrottleTransportAdapter.cs +++ b/src/core/Akka.Remote/Transport/ThrottleTransportAdapter.cs @@ -744,7 +744,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is TokenBucket && Equals((TokenBucket)obj); + return obj is TokenBucket bucket && Equals(bucket); } public override int GetHashCode() @@ -827,7 +827,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is SetThrottle && Equals((SetThrottle)obj); + return obj is SetThrottle throttle && Equals(throttle); } diff --git a/src/core/Akka.Streams.Tests/Dsl/GraphConcatSpec.cs b/src/core/Akka.Streams.Tests/Dsl/GraphConcatSpec.cs index 29a20230bf6..b7a617f005d 100644 --- a/src/core/Akka.Streams.Tests/Dsl/GraphConcatSpec.cs +++ b/src/core/Akka.Streams.Tests/Dsl/GraphConcatSpec.cs @@ -125,7 +125,7 @@ await this.AssertAllStagesStoppedAsync(async() => { foreach (var i in Enumerable.Range(1, 4)) { var result = subscriber2.ExpectNextOrError(); - if (result is int && (int)result == i) + if (result is int result1 && result1 == i) continue; if (result.Equals(TestException())) return; @@ -145,7 +145,7 @@ await this.AssertAllStagesStoppedAsync(async() => { foreach (var i in Enumerable.Range(1, 4)) { var result = subscriber.ExpectNextOrError(); - if (result is int && (int)result == i) + if (result is int result1 && result1 == i) continue; if (result.Equals(TestException())) return; diff --git a/src/core/Akka.Streams/ActorMaterializer.cs b/src/core/Akka.Streams/ActorMaterializer.cs index 2e0f0d80250..20b77c9ed66 100644 --- a/src/core/Akka.Streams/ActorMaterializer.cs +++ b/src/core/Akka.Streams/ActorMaterializer.cs @@ -761,8 +761,8 @@ public override bool Equals(object obj) return false; if (ReferenceEquals(obj, this)) return true; - if (obj is StreamSubscriptionTimeoutSettings) - return Equals((StreamSubscriptionTimeoutSettings) obj); + if (obj is StreamSubscriptionTimeoutSettings settings) + return Equals(settings); return false; } diff --git a/src/core/Akka.Streams/Actors/ActorPublisher.cs b/src/core/Akka.Streams/Actors/ActorPublisher.cs index 2987874b652..32e7c8e767d 100644 --- a/src/core/Akka.Streams/Actors/ActorPublisher.cs +++ b/src/core/Akka.Streams/Actors/ActorPublisher.cs @@ -486,9 +486,8 @@ public void OnErrorThenStop(Exception cause) /// TBD protected internal override bool AroundReceive(Receive receive, object message) { - if (message is Request) + if (message is Request req) { - var req = (Request) message; if (req.IsProcessed) { // it's an unstashed Request, demand is already handled @@ -507,13 +506,12 @@ protected internal override bool AroundReceive(Receive receive, object message) if (_demand < 0) _demand = long.MaxValue; // long overflow: effectively unbounded req.MarkProcessed(); - base.AroundReceive(receive, message); + base.AroundReceive(receive, req); } } } - else if (message is Subscribe) + else if (message is Subscribe sub) { - var sub = (Subscribe) message; var subscriber = sub.Subscriber; switch (_lifecycleState) { diff --git a/src/core/Akka.Streams/Actors/ActorSubscriber.cs b/src/core/Akka.Streams/Actors/ActorSubscriber.cs index 731027661f4..4e074ae70df 100644 --- a/src/core/Akka.Streams/Actors/ActorSubscriber.cs +++ b/src/core/Akka.Streams/Actors/ActorSubscriber.cs @@ -161,9 +161,8 @@ protected internal override bool AroundReceive(Receive receive, object message) Request(RequestStrategy.RequestDemand(RemainingRequested)); } } - else if (message is OnSubscribe) + else if (message is OnSubscribe onSubscribe) { - var onSubscribe = (OnSubscribe) message; if (_subscription == null) { _subscription = onSubscribe.Subscription; diff --git a/src/core/Akka.Streams/Attributes.cs b/src/core/Akka.Streams/Attributes.cs index 85060a16c9f..f2d3747b365 100644 --- a/src/core/Akka.Streams/Attributes.cs +++ b/src/core/Akka.Streams/Attributes.cs @@ -63,7 +63,7 @@ public Name(string value) Value = value; } public bool Equals(Name other) => !ReferenceEquals(other, null) && Equals(Value, other.Value); - public override bool Equals(object obj) => obj is Name && Equals((Name)obj); + public override bool Equals(object obj) => obj is Name name && Equals(name); public override int GetHashCode() => Value.GetHashCode(); public override string ToString() => $"Name({Value})"; } @@ -103,7 +103,7 @@ public bool Equals(InputBuffer other) return Initial == other.Initial && Max == other.Max; } - public override bool Equals(object obj) => obj is InputBuffer && Equals((InputBuffer)obj); + public override bool Equals(object obj) => obj is InputBuffer buffer && Equals(buffer); public override int GetHashCode() { unchecked @@ -159,7 +159,7 @@ public bool Equals(LogLevels other) return OnElement == other.OnElement && OnFinish == other.OnFinish && OnFailure == other.OnFailure; } - public override bool Equals(object obj) => obj is LogLevels && Equals((LogLevels)obj); + public override bool Equals(object obj) => obj is LogLevels levels && Equals(levels); public override int GetHashCode() { unchecked diff --git a/src/core/Akka.Streams/Dsl/BidiFlow.cs b/src/core/Akka.Streams/Dsl/BidiFlow.cs index 7bff82d4933..8b935bb4470 100644 --- a/src/core/Akka.Streams/Dsl/BidiFlow.cs +++ b/src/core/Akka.Streams/Dsl/BidiFlow.cs @@ -30,8 +30,8 @@ public static class BidiFlow public static BidiFlow FromGraph( IGraph, TMat> graph) { - return graph is BidiFlow - ? (BidiFlow) graph + return graph is BidiFlow flow + ? flow : new BidiFlow(graph.Module); } diff --git a/src/core/Akka.Streams/Dsl/GraphDsl.cs b/src/core/Akka.Streams/Dsl/GraphDsl.cs index 324cd2e5c78..8c5bbf80b54 100644 --- a/src/core/Akka.Streams/Dsl/GraphDsl.cs +++ b/src/core/Akka.Streams/Dsl/GraphDsl.cs @@ -142,8 +142,8 @@ public Outlet MaterializedValue * because that computation node would not be part of the tree and * the source would not be triggered. */ - if (_moduleInProgress is CopiedModule) - _moduleInProgress = CompositeModule.Create((Module) _moduleInProgress, _moduleInProgress.Shape); + if (_moduleInProgress is CopiedModule module) + _moduleInProgress = CompositeModule.Create(module, module.Shape); var source = new MaterializedValueSource(_moduleInProgress.MaterializedValueComputation); _moduleInProgress = _moduleInProgress.ComposeNoMaterialized(source.Module); diff --git a/src/core/Akka.Streams/Dsl/RestartFlow.cs b/src/core/Akka.Streams/Dsl/RestartFlow.cs index f752502b65e..34506b3895e 100644 --- a/src/core/Akka.Streams/Dsl/RestartFlow.cs +++ b/src/core/Akka.Streams/Dsl/RestartFlow.cs @@ -445,7 +445,7 @@ public Delay(TimeSpan duration) public bool Equals(Delay other) => !ReferenceEquals(other, null) && Equals(Duration, other.Duration); - public override bool Equals(object obj) => obj is Delay && Equals((Delay)obj); + public override bool Equals(object obj) => obj is Delay delay && Equals(delay); public override int GetHashCode() => Duration.GetHashCode(); diff --git a/src/core/Akka.Streams/Dsl/Sink.cs b/src/core/Akka.Streams/Dsl/Sink.cs index 39cad4fb87f..b8b69137ccf 100644 --- a/src/core/Akka.Streams/Dsl/Sink.cs +++ b/src/core/Akka.Streams/Dsl/Sink.cs @@ -194,8 +194,8 @@ public static class Sink /// TBD /// TBD public static Sink Wrap(IGraph, TMat> graph) - => graph is Sink - ? (Sink)graph + => graph is Sink sink + ? sink : new Sink(graph.Module); /// @@ -631,8 +631,8 @@ public static Sink>> LazyInitAsync(FuncTBD /// TBD public static Sink FromGraph(IGraph, TMat> graph) - => graph is Sink - ? (Sink)graph + => graph is Sink sink + ? sink : new Sink(graph.Module); /// diff --git a/src/core/Akka.Streams/Implementation/ActorMaterializerImpl.cs b/src/core/Akka.Streams/Implementation/ActorMaterializerImpl.cs index 392327fa979..87601b04bd8 100644 --- a/src/core/Akka.Streams/Implementation/ActorMaterializerImpl.cs +++ b/src/core/Akka.Streams/Implementation/ActorMaterializerImpl.cs @@ -650,9 +650,8 @@ public StreamSupervisor(ActorMaterializerSettings settings, AtomicBoolean haveSh /// TBD protected override bool Receive(object message) { - if (message is Materialize) + if (message is Materialize materialize) { - var materialize = (Materialize) message; Sender.Tell(Context.ActorOf(materialize.Props, materialize.Name)); } else if (message is GetChildren) diff --git a/src/core/Akka.Streams/Implementation/ActorProcessor.cs b/src/core/Akka.Streams/Implementation/ActorProcessor.cs index 6a2a853a6a7..4d09d0c0859 100644 --- a/src/core/Akka.Streams/Implementation/ActorProcessor.cs +++ b/src/core/Akka.Streams/Implementation/ActorProcessor.cs @@ -294,10 +294,10 @@ protected virtual bool WaitingForUpstream(object message) { if (message is OnComplete) OnComplete(); - else if (message is OnSubscribe) - OnSubscribe(((OnSubscribe)message).Subscription); - else if (message is OnError) - OnError(((OnError)message).Cause); + else if (message is OnSubscribe subscribe) + OnSubscribe(subscribe.Subscription); + else if (message is OnError error) + OnError(error.Cause); else return false; return true; @@ -310,14 +310,14 @@ protected virtual bool WaitingForUpstream(object message) /// TBD protected virtual bool UpstreamRunning(object message) { - if (message is OnNext) - EnqueueInputElement(((OnNext)message).Element); + if (message is OnNext next) + EnqueueInputElement(next.Element); else if (message is OnComplete) OnComplete(); - else if (message is OnSubscribe) - ((OnSubscribe)message).Subscription.Cancel(); - else if (message is OnError) - OnError(((OnError)message).Cause); + else if (message is OnSubscribe subscribe) + subscribe.Subscription.Cancel(); + else if (message is OnError error) + OnError(error.Cause); else return false; return true; @@ -507,9 +507,9 @@ private void SubscribePending(IEnumerable subscribers) /// TBD protected bool WaitingExposedPublisher(object message) { - if (message is ExposedPublisher) + if (message is ExposedPublisher publisher) { - ExposedPublisher = ((ExposedPublisher)message).Publisher; + ExposedPublisher = publisher.Publisher; SubReceive.Become(DownstreamRunning); return true; } @@ -526,9 +526,8 @@ protected bool DownstreamRunning(object message) { if (message is SubscribePending) SubscribePending(ExposedPublisher.TakePendingSubscribers()); - else if (message is RequestMore) + else if (message is RequestMore requestMore) { - var requestMore = (RequestMore)message; if (requestMore.Demand < 1) Error(ReactiveStreamsCompliance.NumberOfElementsInRequestMustBePositiveException); else diff --git a/src/core/Akka.Streams/Implementation/ActorRefSourceActor.cs b/src/core/Akka.Streams/Implementation/ActorRefSourceActor.cs index 994be0aad6d..cc33097ea59 100644 --- a/src/core/Akka.Streams/Implementation/ActorRefSourceActor.cs +++ b/src/core/Akka.Streams/Implementation/ActorRefSourceActor.cs @@ -76,7 +76,7 @@ public ActorRefSourceActor(int bufferSize, OverflowStrategy overflowStrategy, in /// TBD /// TBD protected override bool Receive(object message) - => DefaultReceive(message) || RequestElement(message) || (message is T && ReceiveElement((T)message)); + => DefaultReceive(message) || RequestElement(message) || (message is T message1 && ReceiveElement(message1)); /// /// TBD diff --git a/src/core/Akka.Streams/Implementation/Fusing/Fusing.cs b/src/core/Akka.Streams/Implementation/Fusing/Fusing.cs index 22c553349a3..06ae087b70f 100644 --- a/src/core/Akka.Streams/Implementation/Fusing/Fusing.cs +++ b/src/core/Akka.Streams/Implementation/Fusing/Fusing.cs @@ -294,10 +294,10 @@ private static GraphModule FuseGroup(BuildStructuralInfo info, ISet gro outOwnersB3.CopyTo(outOwners, outStart); var firstModule = group.First(); - if(!(firstModule is CopiedModule)) + if(!(firstModule is CopiedModule module)) throw new ArgumentException("unexpected module structure"); - var asyncAttrs = IsAsync((CopiedModule) firstModule) ? new Attributes(Attributes.AsyncBoundary.Instance) : Attributes.None; - var dispatcher = GetDispatcher(firstModule); + var asyncAttrs = IsAsync(module) ? new Attributes(Attributes.AsyncBoundary.Instance) : Attributes.None; + var dispatcher = GetDispatcher(module); var dispatcherAttrs = dispatcher == null ? Attributes.None : new Attributes(dispatcher); var attr = asyncAttrs.And(dispatcherAttrs); @@ -820,9 +820,9 @@ public Atomic AddModule(IModule module, ISet group, Attributes inherite if (IsCopiedModuleWithGraphStageAndMaterializedValue(copy)) PushMaterializationSource((CopiedModule) copy); - else if (copy is GraphModule) + else if (copy is GraphModule graphModule) { - var mvids = ((GraphModule) copy).MaterializedValueIds; + var mvids = graphModule.MaterializedValueIds; foreach (IModule mvid in mvids) { if (IsCopiedModuleWithGraphStageAndMaterializedValue(mvid)) diff --git a/src/core/Akka.Streams/Implementation/Fusing/GraphAssembly.cs b/src/core/Akka.Streams/Implementation/Fusing/GraphAssembly.cs index af3556648f2..a9f55d87a01 100644 --- a/src/core/Akka.Streams/Implementation/Fusing/GraphAssembly.cs +++ b/src/core/Akka.Streams/Implementation/Fusing/GraphAssembly.cs @@ -202,9 +202,9 @@ public GraphAssembly(IGraphStageWithMaterializedValue[] stages, A } var stage = Stages[i]; - if (stage is IMaterializedValueSource) + if (stage is IMaterializedValueSource source) { - var copy = ((IMaterializedValueSource) stage).CopySource(); + var copy = source.CopySource(); register(copy); stage = (IGraphStageWithMaterializedValue)copy; } diff --git a/src/core/Akka.Streams/Implementation/Fusing/GraphStages.cs b/src/core/Akka.Streams/Implementation/Fusing/GraphStages.cs index 91157d8a129..db9d2889829 100644 --- a/src/core/Akka.Streams/Implementation/Fusing/GraphStages.cs +++ b/src/core/Akka.Streams/Implementation/Fusing/GraphStages.cs @@ -410,8 +410,8 @@ public FlowMonitor.IStreamState State get { var value = Value; - if (value is T) - return new FlowMonitor.Received((T)value); + if (value is T value1) + return new FlowMonitor.Received(value1); return value as FlowMonitor.IStreamState; } diff --git a/src/core/Akka.Streams/Implementation/Fusing/StreamOfStreams.cs b/src/core/Akka.Streams/Implementation/Fusing/StreamOfStreams.cs index 4e2d97da9c2..188f9dc6083 100644 --- a/src/core/Akka.Streams/Implementation/Fusing/StreamOfStreams.cs +++ b/src/core/Akka.Streams/Implementation/Fusing/StreamOfStreams.cs @@ -1243,8 +1243,8 @@ private void SetCallback(Action callback) } else if (status is OnComplete) CompleteStage(); - else if (status is OnError) - FailStage(((OnError) status).Cause); + else if (status is OnError error) + FailStage(error.Cause); else if (status is Action) throw new IllegalStateException("Substream Source cannot be materialized more than once"); } @@ -1255,10 +1255,10 @@ public override void PreStart() { if (msg is OnComplete) CompleteStage(); - else if (msg is OnError) - FailStage(((OnError) msg).Cause); - else if (msg is OnNext) - Push(_stage._out, (T) ((OnNext) msg).Element); + else if (msg is OnError error) + FailStage(error.Cause); + else if (msg is OnNext next) + Push(_stage._out, (T) next.Element); }); SetCallback(ourOwnCallback); } diff --git a/src/core/Akka.Streams/Implementation/IO/TcpStages.cs b/src/core/Akka.Streams/Implementation/IO/TcpStages.cs index cf93f7b90af..cce2f2dc20a 100644 --- a/src/core/Akka.Streams/Implementation/IO/TcpStages.cs +++ b/src/core/Akka.Streams/Implementation/IO/TcpStages.cs @@ -487,9 +487,8 @@ public override void PreStart() { SetKeepGoing(true); - if (_role is Inbound) + if (_role is Inbound inbound) { - var inbound = (Inbound)_role; SetHandler(_bytesOut, _readHandler); _connection = inbound.Connection; GetStageActor(Connected).Watch(_connection); @@ -509,9 +508,8 @@ public override void PreStart() /// public override void PostStop() { - if (_role is Outbound) + if (_role is Outbound outbound) { - var outbound = (Outbound)_role; // Fail if has not been completed with an address earlier outbound.LocalAddressPromise.TrySetException(new StreamTcpException("Connection failed")); } @@ -526,12 +524,10 @@ private StageActorRef.Receive Connecting(Outbound outbound) if (msg is Terminated) FailStage(new StreamTcpException("The IO manager actor (TCP) has terminated. Stopping now.")); - else if (msg is Tcp.CommandFailed) - FailStage(new StreamTcpException($"Tcp command {((Tcp.CommandFailed)msg).Cmd} failed")); - else if (msg is Tcp.Connected) + else if (msg is Tcp.CommandFailed failed) + FailStage(new StreamTcpException($"Tcp command {failed.Cmd} failed")); + else if (msg is Tcp.Connected connected) { - var connected = (Tcp.Connected)msg; - ((Outbound)_role).LocalAddressPromise.TrySetResult(connected.LocalAddress); _connection = sender; SetHandler(_bytesOut, _readHandler); @@ -554,15 +550,14 @@ private void Connected((IActorRef, object) args) var msg = args.Item2; if (msg is Terminated) FailStage(new StreamTcpException("The connection actor has terminated. Stopping now.")); - else if (msg is Tcp.CommandFailed) FailStage(new StreamTcpException($"Tcp command {((Tcp.CommandFailed)msg).Cmd} failed")); - else if (msg is Tcp.ErrorClosed) FailStage(new StreamTcpException($"The connection closed with error: {((Tcp.ErrorClosed)msg).Cause}")); + else if (msg is Tcp.CommandFailed failed) FailStage(new StreamTcpException($"Tcp command {failed.Cmd} failed")); + else if (msg is Tcp.ErrorClosed closed) FailStage(new StreamTcpException($"The connection closed with error: {closed.Cause}")); else if (msg is Tcp.Aborted) FailStage(new StreamTcpException("The connection has been aborted")); else if (msg is Tcp.Closed) CompleteStage(); else if (msg is Tcp.ConfirmedClosed) CompleteStage(); else if (msg is Tcp.PeerClosed) Complete(_bytesOut); - else if (msg is Tcp.Received) + else if (msg is Tcp.Received received) { - var received = (Tcp.Received)msg; // Keep on reading even when closed. There is no "close-read-side" in TCP if (IsClosed(_bytesOut)) _connection.Tell(Tcp.ResumeReading.Instance, StageActor.Ref); else Push(_bytesOut, received.Data); diff --git a/src/core/Akka.Streams/Implementation/StreamLayout.cs b/src/core/Akka.Streams/Implementation/StreamLayout.cs index 37cd9ca0d7b..b20746a5fd3 100644 --- a/src/core/Akka.Streams/Implementation/StreamLayout.cs +++ b/src/core/Akka.Streams/Implementation/StreamLayout.cs @@ -268,7 +268,7 @@ public static void Validate(IModule module, int level = 0, bool shouldPrint = fa var atomics = Atomics(module.MaterializedValueComputation); var graphValues = module.SubModules.SelectMany( - m => m is GraphModule ? ((GraphModule) m).MaterializedValueIds : Enumerable.Empty()); + m => m is GraphModule graphModule ? graphModule.MaterializedValueIds : Enumerable.Empty()); var nonExistent = atomics.Except(module.SubModules).Except(graphValues).Except(new[] {module}); if (nonExistent.Any()) problems.Add("computation refers to non-existent modules " + string.Join(", ", nonExistent)); diff --git a/src/core/Akka.Streams/Implementation/Transfer.cs b/src/core/Akka.Streams/Implementation/Transfer.cs index b299cc64416..e12adf8ad1f 100644 --- a/src/core/Akka.Streams/Implementation/Transfer.cs +++ b/src/core/Akka.Streams/Implementation/Transfer.cs @@ -589,16 +589,15 @@ public static void WaitForUpstream(this IPump self, int waitForUpstream) /// TBD public static void GotUpstreamSubscription(this IPump self) { - if (self.TransferState is WaitingForUpstreamSubscription) + if (self.TransferState is WaitingForUpstreamSubscription state) { - var t = (WaitingForUpstreamSubscription) self.TransferState; - if (t.Remaining == 1) + if (state.Remaining == 1) { - self.TransferState = t.AndThen.Precondition; - self.CurrentAction = t.AndThen.Action; + self.TransferState = state.AndThen.Precondition; + self.CurrentAction = state.AndThen.Action; } else - self.TransferState = new WaitingForUpstreamSubscription(t.Remaining - 1, t.AndThen); + self.TransferState = new WaitingForUpstreamSubscription(state.Remaining - 1, state.AndThen); } self.Pump(); @@ -611,10 +610,9 @@ public static void GotUpstreamSubscription(this IPump self) /// TBD public static void NextPhase(this IPump self, TransferPhase phase) { - if (self.TransferState is WaitingForUpstreamSubscription) + if (self.TransferState is WaitingForUpstreamSubscription state) { - var w = (WaitingForUpstreamSubscription) self.TransferState; - self.TransferState = new WaitingForUpstreamSubscription(w.Remaining, phase); + self.TransferState = new WaitingForUpstreamSubscription(state.Remaining, phase); } else { diff --git a/src/core/Akka.Streams/Implementation/UntypedPublisher.cs b/src/core/Akka.Streams/Implementation/UntypedPublisher.cs index 6fead868260..e065351032f 100644 --- a/src/core/Akka.Streams/Implementation/UntypedPublisher.cs +++ b/src/core/Akka.Streams/Implementation/UntypedPublisher.cs @@ -68,8 +68,8 @@ public static UntypedPublisher FromTyped(IPublisher publisher) /// TBD public static object ToTyped(IUntypedPublisher untypedPublisher) { - if (untypedPublisher is UntypedPublisher) - return ((UntypedPublisher) untypedPublisher).Unwrap(); + if (untypedPublisher is UntypedPublisher publisher) + return publisher.Unwrap(); return untypedPublisher; } diff --git a/src/core/Akka.Streams/Implementation/UntypedSubscriber.cs b/src/core/Akka.Streams/Implementation/UntypedSubscriber.cs index 399dc2bd449..75121db6158 100644 --- a/src/core/Akka.Streams/Implementation/UntypedSubscriber.cs +++ b/src/core/Akka.Streams/Implementation/UntypedSubscriber.cs @@ -100,8 +100,8 @@ public static UntypedSubscriber FromTyped(ISubscriber subscriber) /// TBD public static object ToTyped(IUntypedSubscriber untypedSubscriber) { - if (untypedSubscriber is UntypedSubscriber) - return ((UntypedSubscriber) untypedSubscriber).Unwrap(); + if (untypedSubscriber is UntypedSubscriber subscriber) + return subscriber.Unwrap(); return untypedSubscriber; } diff --git a/src/core/Akka.Streams/Implementation/UntypedVirtualPublisher.cs b/src/core/Akka.Streams/Implementation/UntypedVirtualPublisher.cs index dd002eeee91..180514cd26e 100644 --- a/src/core/Akka.Streams/Implementation/UntypedVirtualPublisher.cs +++ b/src/core/Akka.Streams/Implementation/UntypedVirtualPublisher.cs @@ -78,8 +78,8 @@ public static UntypedVirtualPublisher FromTyped(VirtualPublisher publisher /// TBD public static object ToTyped(IUntypedVirtualPublisher untypedPublisher) { - if (untypedPublisher is UntypedVirtualPublisher) - return ((UntypedVirtualPublisher) untypedPublisher).Unwrap(); + if (untypedPublisher is UntypedVirtualPublisher publisher) + return publisher.Unwrap(); return untypedPublisher; } diff --git a/src/core/Akka.Streams/Stage/Stage.cs b/src/core/Akka.Streams/Stage/Stage.cs index fec48bc75b1..7b6260ec97f 100644 --- a/src/core/Akka.Streams/Stage/Stage.cs +++ b/src/core/Akka.Streams/Stage/Stage.cs @@ -418,9 +418,8 @@ private StageState EmittingState(IEnumerator enumerator, Statef _isEmitting = false; if (andThen is StatefulStage.Stay) ; - else if (andThen is StatefulStage.Become) + else if (andThen is StatefulStage.Become become) { - var become = andThen as StatefulStage.Become; Become(become.State); } else if (andThen is StatefulStage.Finish) diff --git a/src/core/Akka.TestKit.Tests/TestActorRefTests/BossActor.cs b/src/core/Akka.TestKit.Tests/TestActorRefTests/BossActor.cs index c84abd37919..f55b96e1f04 100644 --- a/src/core/Akka.TestKit.Tests/TestActorRefTests/BossActor.cs +++ b/src/core/Akka.TestKit.Tests/TestActorRefTests/BossActor.cs @@ -29,7 +29,7 @@ protected override SupervisorStrategy SupervisorStrategy() protected override bool ReceiveMessage(object message) { - if(message is string && ((string)message) == "sendKill") + if(message is string s && s == "sendKill") { _child.Tell(Kill.Instance); return true; diff --git a/src/core/Akka.TestKit.Tests/TestActorRefTests/Logger.cs b/src/core/Akka.TestKit.Tests/TestActorRefTests/Logger.cs index 02c5dc9a491..f3482ffa049 100644 --- a/src/core/Akka.TestKit.Tests/TestActorRefTests/Logger.cs +++ b/src/core/Akka.TestKit.Tests/TestActorRefTests/Logger.cs @@ -17,10 +17,10 @@ public class Logger : ActorBase protected override bool Receive(object message) { var warning = message as Warning; - if(warning != null && warning.Message is string) + if(warning != null && warning.Message is string warningMessage) { _count++; - _msg = (string)warning.Message; + _msg = warningMessage; return true; } return false; diff --git a/src/core/Akka.TestKit.Tests/TestActorRefTests/WorkerActor.cs b/src/core/Akka.TestKit.Tests/TestActorRefTests/WorkerActor.cs index e2d31de3645..cfd497658a9 100644 --- a/src/core/Akka.TestKit.Tests/TestActorRefTests/WorkerActor.cs +++ b/src/core/Akka.TestKit.Tests/TestActorRefTests/WorkerActor.cs @@ -27,9 +27,9 @@ protected override bool ReceiveMessage(object message) } //TODO: case replyTo: Promise[_] ⇒ replyTo.asInstanceOf[Promise[Any]].success("complexReply") - if(message is IActorRef) + if(message is IActorRef @ref) { - ((IActorRef)message).Tell("complexReply", Self); + @ref.Tell("complexReply", Self); return true; } return false; diff --git a/src/core/Akka.TestKit/EventFilter/EventFilterFactory.cs b/src/core/Akka.TestKit/EventFilter/EventFilterFactory.cs index 7b88c86dd6c..f9ab2dedcfa 100644 --- a/src/core/Akka.TestKit/EventFilter/EventFilterFactory.cs +++ b/src/core/Akka.TestKit/EventFilter/EventFilterFactory.cs @@ -185,7 +185,7 @@ public IEventFilterApplier Custom(Predicate predicate) /// TBD public IEventFilterApplier Custom(Predicate predicate) where TLogEvent : LogEvent { - var filter = new CustomEventFilter(logEvent => logEvent is TLogEvent && predicate((TLogEvent)logEvent)); + var filter = new CustomEventFilter(logEvent => logEvent is TLogEvent @event && predicate(@event)); return CreateApplier(filter, _system); } @@ -281,7 +281,7 @@ public IEventFilterApplier DeadLetter(string source = null) /// TBD public IEventFilterApplier DeadLetter(Func isMatch, string source = null) { - return DeadLetter(deadLetter => deadLetter.Message is TMessage && isMatch((TMessage)deadLetter.Message), source); + return DeadLetter(deadLetter => deadLetter.Message is TMessage message && isMatch(message), source); } /// diff --git a/src/core/Akka.TestKit/TestKitBase.cs b/src/core/Akka.TestKit/TestKitBase.cs index 3d4f1a8d434..21a4ac54b39 100644 --- a/src/core/Akka.TestKit/TestKitBase.cs +++ b/src/core/Akka.TestKit/TestKitBase.cs @@ -331,7 +331,7 @@ public void IgnoreMessages(Func shouldIgnoreMessage) /// true the message will be ignored by . public void IgnoreMessages(Func shouldIgnoreMessage) { - _testState.TestActor.Tell(new TestActor.SetIgnore(m => m is TMsg && shouldIgnoreMessage((TMsg)m))); + _testState.TestActor.Tell(new TestActor.SetIgnore(m => m is TMsg msg && shouldIgnoreMessage(msg))); } /// diff --git a/src/core/Akka.Tests.Performance/Actor/ActorThroughputSpec.cs b/src/core/Akka.Tests.Performance/Actor/ActorThroughputSpec.cs index 087fe64d385..3917891ecea 100644 --- a/src/core/Akka.Tests.Performance/Actor/ActorThroughputSpec.cs +++ b/src/core/Akka.Tests.Performance/Actor/ActorThroughputSpec.cs @@ -36,19 +36,16 @@ public BenchmarkUntypedActor(Counter counter, long maxExpectedMessages, ManualRe protected override void OnReceive(object message) { - if (message is string) + if (message is string stringMessage) { - string stringMessage = (string)message; IncrementAndCheck(); } - else if (message is int) + else if (message is int intMessage) { - int intMessage = (int)message; IncrementAndCheck(); } - else if (message is SimpleData) + else if (message is SimpleData simpleDataMessage) { - SimpleData simpleDataMessage = (SimpleData)message; if (simpleDataMessage.Age > 20) { IncrementAndCheck(); diff --git a/src/core/Akka.Tests.Shared.Internals/Helpers/XAssert.cs b/src/core/Akka.Tests.Shared.Internals/Helpers/XAssert.cs index 3e885204b7d..95092daf37c 100644 --- a/src/core/Akka.Tests.Shared.Internals/Helpers/XAssert.cs +++ b/src/core/Akka.Tests.Shared.Internals/Helpers/XAssert.cs @@ -53,9 +53,9 @@ public static T Throws(Action action) where T : Exception } catch(Exception ex) { - if(ex is T) + if(ex is T exception1) { - return (T) ex; + return exception1; } exception = ex; } diff --git a/src/core/Akka.Tests/Actor/ActorLifeCycleSpec.cs b/src/core/Akka.Tests/Actor/ActorLifeCycleSpec.cs index 63b65b5afd1..400b64cafee 100644 --- a/src/core/Akka.Tests/Actor/ActorLifeCycleSpec.cs +++ b/src/core/Akka.Tests/Actor/ActorLifeCycleSpec.cs @@ -41,7 +41,7 @@ private void Report(object message) protected override void OnReceive(object message) { - if (message is string && (string)message == "status") + if (message is string s && s == "status") { testActor.Tell(("OK",id,CurrentGeneration)); } @@ -89,7 +89,7 @@ private void Report(object message) protected override void OnReceive(object message) { - if (message is string && (string)message == "status") + if (message is string s && s == "status") { testActor.Tell(("OK", id, CurrentGeneration)); } diff --git a/src/core/Akka.Tests/Actor/ActorRefSpec.cs b/src/core/Akka.Tests/Actor/ActorRefSpec.cs index 391a6e90b8b..b2896061038 100644 --- a/src/core/Akka.Tests/Actor/ActorRefSpec.cs +++ b/src/core/Akka.Tests/Actor/ActorRefSpec.cs @@ -592,9 +592,8 @@ private class PoisonPilledActor : ActorBase { protected override bool Receive(object message) { - if (message is int) + if (message is int i) { - var i = (int)message; string msg = null; if (i == 0) msg = "zero"; else if (i == 5) msg = "five"; diff --git a/src/core/Akka.Tests/Actor/FSMTimingSpec.cs b/src/core/Akka.Tests/Actor/FSMTimingSpec.cs index 360d09091d6..a7e87f1a8af 100644 --- a/src/core/Akka.Tests/Actor/FSMTimingSpec.cs +++ b/src/core/Akka.Tests/Actor/FSMTimingSpec.cs @@ -278,10 +278,9 @@ public StateMachine(IActorRef tester) When(FsmState.Initial, @event => { - if (@event.FsmEvent is FsmState) + if (@event.FsmEvent is FsmState name) { - var s = (FsmState)@event.FsmEvent; - switch (s) + switch (name) { case FsmState.TestSingleTimer: SetTimer("tester", Tick.Instance, 500.Milliseconds(), false); @@ -292,7 +291,7 @@ public StateMachine(IActorRef tester) case FsmState.TestStateTimeoutOverride: return GoTo(FsmState.TestStateTimeout).ForMax(TimeSpan.MaxValue); default: - return GoTo(s); + return GoTo(name); } } return null; @@ -454,9 +453,8 @@ public StoppingActor() When(FsmState.Initial, evt => { - if (evt.FsmEvent is FsmState) + if (evt.FsmEvent is FsmState state) { - var state = (FsmState)evt.FsmEvent; if (state == FsmState.TestStoppingActorStateTimeout) { Context.Stop(Self); diff --git a/src/core/Akka.Tests/Actor/RemotePathParsingSpec.cs b/src/core/Akka.Tests/Actor/RemotePathParsingSpec.cs index 2792cea9638..ad20fd91316 100644 --- a/src/core/Akka.Tests/Actor/RemotePathParsingSpec.cs +++ b/src/core/Akka.Tests/Actor/RemotePathParsingSpec.cs @@ -50,8 +50,8 @@ public static Arbitrary AllEndpoints() public static string ExtractHost(EndPoint endpoint) { - if (endpoint is IPEndPoint) - return ((IPEndPoint)endpoint).Address.ToString(); + if (endpoint is IPEndPoint point) + return point.Address.ToString(); return ((DnsEndPoint)endpoint).Host; } diff --git a/src/core/Akka.Tests/MatchHandler/MatchExpressionBuilder_BuildLambdaExpression_Tests.cs b/src/core/Akka.Tests/MatchHandler/MatchExpressionBuilder_BuildLambdaExpression_Tests.cs index 5d94765ed89..d552c16309a 100644 --- a/src/core/Akka.Tests/MatchHandler/MatchExpressionBuilder_BuildLambdaExpression_Tests.cs +++ b/src/core/Akka.Tests/MatchHandler/MatchExpressionBuilder_BuildLambdaExpression_Tests.cs @@ -423,7 +423,7 @@ public void Build_one_action_that_expects_base_type() //Handle a string with one action var typeHandlers = new List(); var stringHandler = new TypeHandler(typeof(string)); - Action action = s => { updatedValue = s is string ? "WasString:" + (string)s : "WasNotString" + s.ToString(); }; + Action action = s => { updatedValue = s is string s1 ? "WasString:" + s1 : "WasNotString" + s.ToString(); }; var handler = PredicateAndHandler.CreateAction(action, handlerFirstArgumentShouldBeBaseType: true); stringHandler.Handlers.Add(handler); typeHandlers.Add(stringHandler); diff --git a/src/core/Akka/Actor/BuiltInActors.cs b/src/core/Akka/Actor/BuiltInActors.cs index 0644eee735c..36eb50cc80f 100644 --- a/src/core/Akka/Actor/BuiltInActors.cs +++ b/src/core/Akka/Actor/BuiltInActors.cs @@ -43,8 +43,8 @@ protected override bool Receive(object message) { if (message is Terminated) Context.Stop(Self); - else if (message is StopChild) - Context.Stop(((StopChild)message).Child); + else if (message is StopChild child) + Context.Stop(child.Child); else Context.System.DeadLetters.Tell(new DeadLetter(message, Sender, Self), Sender); return true; diff --git a/src/core/Akka/Actor/CoordinatedShutdown.cs b/src/core/Akka/Actor/CoordinatedShutdown.cs index e56cc2aca04..475088d4ab4 100644 --- a/src/core/Akka/Actor/CoordinatedShutdown.cs +++ b/src/core/Akka/Actor/CoordinatedShutdown.cs @@ -91,7 +91,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Phase && Equals((Phase)obj); + return obj is Phase phase && Equals(phase); } /// diff --git a/src/core/Akka/Actor/IAutoReceivedMessage.cs b/src/core/Akka/Actor/IAutoReceivedMessage.cs index 544542ca948..c5c7fe28b84 100644 --- a/src/core/Akka/Actor/IAutoReceivedMessage.cs +++ b/src/core/Akka/Actor/IAutoReceivedMessage.cs @@ -114,7 +114,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Identify && Equals((Identify)obj); + return obj is Identify identify && Equals(identify); } @@ -169,7 +169,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is ActorIdentity && Equals((ActorIdentity)obj); + return obj is ActorIdentity identity && Equals(identity); } diff --git a/src/core/Akka/Actor/RepointableActorRef.cs b/src/core/Akka/Actor/RepointableActorRef.cs index dbc991a04e1..2128e3a12aa 100644 --- a/src/core/Akka/Actor/RepointableActorRef.cs +++ b/src/core/Akka/Actor/RepointableActorRef.cs @@ -521,8 +521,8 @@ public bool TryGetChildStatsByName(string name, out IChildStats child) /// TBD public void SendMessage(IActorRef sender, object message) { - if (message is ISystemMessage) - SendSystemMessage((ISystemMessage)message); + if (message is ISystemMessage systemMessage) + SendSystemMessage(systemMessage); else SendMessage(message, sender); } diff --git a/src/core/Akka/Dispatch/CachingConfig.cs b/src/core/Akka/Dispatch/CachingConfig.cs index cb7cc02a102..ffd0efe230e 100644 --- a/src/core/Akka/Dispatch/CachingConfig.cs +++ b/src/core/Akka/Dispatch/CachingConfig.cs @@ -286,9 +286,9 @@ public override double GetDouble(string path, double @default = 0) public override string GetString(string path, string @default = null) { var pathEntry = GetPathEntry(path); - if (pathEntry is StringPathEntry) + if (pathEntry is StringPathEntry entry) { - return ((StringPathEntry)pathEntry).Value; + return entry.Value; } else { diff --git a/src/core/Akka/Dispatch/SysMsg/ISystemMessage.cs b/src/core/Akka/Dispatch/SysMsg/ISystemMessage.cs index 2eb5a8a4af1..cc37c4341e9 100644 --- a/src/core/Akka/Dispatch/SysMsg/ISystemMessage.cs +++ b/src/core/Akka/Dispatch/SysMsg/ISystemMessage.cs @@ -543,7 +543,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Unwatch && Equals((Unwatch)obj); + return obj is Unwatch unwatch && Equals(unwatch); } public override int GetHashCode() @@ -840,7 +840,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is Create && Equals((Create)obj); + return obj is Create create && Equals(create); } public override int GetHashCode() diff --git a/src/core/Akka/Serialization/ByteArraySerializer.cs b/src/core/Akka/Serialization/ByteArraySerializer.cs index 6d69779fc74..6718138fba9 100644 --- a/src/core/Akka/Serialization/ByteArraySerializer.cs +++ b/src/core/Akka/Serialization/ByteArraySerializer.cs @@ -42,8 +42,8 @@ public override byte[] ToBinary(object obj) { if (obj == null) return null; - if (obj is byte[]) - return (byte[]) obj; + if (obj is byte[] bytes) + return bytes; throw new NotSupportedException("The object to convert is not a byte array."); } diff --git a/src/core/Akka/Serialization/NewtonSoftJsonSerializer.cs b/src/core/Akka/Serialization/NewtonSoftJsonSerializer.cs index e906cf0abf8..ff161f75cca 100644 --- a/src/core/Akka/Serialization/NewtonSoftJsonSerializer.cs +++ b/src/core/Akka/Serialization/NewtonSoftJsonSerializer.cs @@ -486,12 +486,12 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s private object GetString(object value) { - if (value is int) - return "I" + ((int)value).ToString(NumberFormatInfo.InvariantInfo); - if (value is float) - return "F" + ((float)value).ToString(NumberFormatInfo.InvariantInfo); - if (value is decimal) - return "M" + ((decimal)value).ToString(NumberFormatInfo.InvariantInfo); + if (value is int i) + return "I" + i.ToString(NumberFormatInfo.InvariantInfo); + if (value is float f) + return "F" + f.ToString(NumberFormatInfo.InvariantInfo); + if (value is decimal value1) + return "M" + value1.ToString(NumberFormatInfo.InvariantInfo); throw new NotSupportedException(); } } diff --git a/src/core/Akka/Util/Result.cs b/src/core/Akka/Util/Result.cs index ec33930757d..a04b86ff956 100644 --- a/src/core/Akka/Util/Result.cs +++ b/src/core/Akka/Util/Result.cs @@ -65,7 +65,7 @@ public bool Equals(Result other) public override bool Equals(object obj) { - if (obj is Result) return Equals((Result) obj); + if (obj is Result result) return Equals(result); return false; }