I'm searching for a way to make it illegal for the user of a method to ignore the returned object/value of a method. In C++, this is possible with the [[nodiscard]] attribute. However, I couldn't find a similar attribute in C#. Is there a standard implementation of such an attribute or a convention on how to achieve this behaviour?
As an example why this may be useful:
var date = new DateOnly(2023, 8, 23);
date.AddDays(10);
if (date == new DateOnly(2023, 8, 23))
{
Console.WriteLine("AddDays returns a new instance and does not modify the instance itself. [[nodiscard]] would prevent this");
}
[[nodiscard]] has two analogs in C#/.Net. The first is the poorly named [Pure] attribute which was originally intended to document that a method has no side effects. If the return value of a method marked [Pure] is discarded, code-analysis warning CA1806 is raised in the editor (but not on build by default).
There's also ongoing work to add [return: DoNotIgnore] to the language, but that is as of March 2023 is still in development.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With