Search code examples
c#performanceattributes

Is Pure attribute useless?


I found PureAttribute in .NET source code (System.Diagnostics.Contracts.PureAttribute) and here is the summary:

Indicates that a type or method is pure, that is, it does not make any visible state changes. I checked here lowered C#

I checked ever in debug mode Debug -> windows -> Disassembly and the code is exactly the same. So what is the different? I found that "There is a contract" etc. or "if we send the same parameters always we get the same result". Ok, got it but if it change nothing we it exists? No performance? No readability? And what is that contract?

I expect get answers for these questions:

  • If it changes nothing why does it exist? No performance? No readability?
  • What is that contract?

Solution

  • The original purpose of the [Pure] attribute appears to have been to support the old "Code Contracts" analysis, which sadly is no longer being developed.

    The [Pure] attribute is not used in any code analysis:

    This attribute is not enforced by the current analysis tools

    Now the only purpose is for documenting the fact that a method does not cause any observable state change - but unfortunately no code analysis tools that I know of actually enforce this.

    There is one Resharper warning which is provoked by the [Pure] attribute: If you ignore the return value of a pure method, Resharper will warn you. Other than that, nothing seems to warn you if you modify observable state in a pure method or change the state of a pure parameter, as the following code demonstrates:

    using System;
    using System.Diagnostics.Contracts;
    
    namespace Console1;
    
    public static class Program
    {
        static void Main(string[] args)
        {
            CalculateSomething(); // Resharper warning: "Return value of pure method not used".
            ChangeSomething();    // Resharper warning: "Return value of pure method not used".
            DoSomething();        // No warnings.
        }
    
        [Pure] public static int CalculateSomething()
        {
            return _field;
        }
    
        [Pure] public static int ChangeSomething()
        {
            _field = 1; // Provokes NO warning.
            return 42;
        }
    
        public static int DoSomething()
        {
            return _field;
        }
    
        public static void ChangeParameter([Pure] Random rng)
        {
            _ = rng.Next(); // No warning about calling impure method of pure parameter.
        }
    
        static int _field;
    
    }
    

    Microsoft's Code Analysis will also issue a similar warning, CA1806, if you fail to observe the return value of a pure method.