Search code examples
c#parametersattributes

What's the use case of method parameter attributes?


Putting in Equals and hashcode overrides I had the NotNullWhen attribute autocomplete when making the method - reading the documentation my understanding is that it basically says that when Equals returns true, the parameter obj being fed in will not be null. Why would I ever want to have this attribute? This is sitting in a struct which can't be null, and the override wouldn't allow for a null parameter to ever return true anyway. Does having this attribute really matter at all? It's not enforcing that logic either right?

public override bool Equals([NotNullWhen(true)] object? obj)
        {
            return (obj is Time time && Hour == time.Hour && Minute == time.Minute);
        }

Solution

  • Method parameter attributes, writ large, have a number of uses. For example, they can be used to direct web frameworks to populate the parameter by serializing the body of an HTTP request. Some will direct the compiler to automatically provide a value for an optional parameter in cases where none is explicitly provided.

    Attributes like the one in your example are designed to make life easier for the consumer of your method. For example, if someone uses your class like this:

    Time? providedTime = GetTimeFromInputs();
    if(targetTime.Equals(providedTime))
    {
        DoSomethingWith(providedTime.Hour, providedTime.Minute)
    }
    

    Without the attribute on the Equals method, the C# compiler and analyzers will very helpfully warn the developer that providedTime.Hour might throw a null reference exception. The developer might intuitively know there's no way that could happen when Equals returned true, but the IDE still gives them an annoying little yellow squiggly. With the attribute in place, the compiler knows enough not to give you that false warning.