diff --git a/src/Wolfgang.TryPattern/Result.cs b/src/Wolfgang.TryPattern/Result.cs index b366f44..bc53a71 100644 --- a/src/Wolfgang.TryPattern/Result.cs +++ b/src/Wolfgang.TryPattern/Result.cs @@ -58,10 +58,20 @@ public static Result Failure(string errorMessage) => + private static readonly Result _successInstance = new(succeeded: true, string.Empty); + + + /// /// Creates a successful . /// - public static Result Success() => new(succeeded: true, string.Empty); + /// + /// Returns a cached singleton instance. is immutable, so reusing + /// the same instance is safe and avoids per-call allocations on hot paths. Callers must + /// not rely on reference identity to distinguish results: every call to + /// returns the same object, so two successful results will be reference-equal. + /// + public static Result Success() => _successInstance; diff --git a/tests/Wolfgang.TryPattern.Tests/ResultTests.cs b/tests/Wolfgang.TryPattern.Tests/ResultTests.cs index 99d6e35..da14204 100644 --- a/tests/Wolfgang.TryPattern.Tests/ResultTests.cs +++ b/tests/Wolfgang.TryPattern.Tests/ResultTests.cs @@ -61,6 +61,22 @@ public void Success_sets_properties_correctly() + [Fact] + public void Success_returns_the_same_cached_instance_on_every_call() + { + // Locks in the singleton optimization: Result is immutable, so + // Success() intentionally returns a shared instance to avoid + // per-call allocations. If this assertion ever needs to be + // relaxed, it is a deliberate behavioral change that consumers + // relying on reference identity should be notified about. + var first = Result.Success(); + var second = Result.Success(); + + Assert.Same(first, second); + } + + + [Fact] public void Failure_sets_properties_correctly() {