Marking pure functions with the Pure attribute
Understanding the role of pure functions and side effects in our code is crucial for effective functional programming in C#. But how do we communicate our intent that a function should be pure? This is where the Pure
attribute comes into play.
Understanding the Pure attribute in C#
In C#, the Pure
attribute is defined in the System.Diagnostics.Contracts
namespace and serves as a declarative tag to indicate that a method is pure. A pure method is one that, given the same inputs, will always return the same output and does not produce any observable side effects.
It’s important to note that the Pure
attribute is primarily intended for use in code contracts and static checking tools. The runtime and compiler don’t enforce the purity of a method, and this attribute does not change the method’s behavior in any way:
[Pure] public static decimal CalculateRoyalty(decimal bookPrice, decimal royaltyPercent) { ...