Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodiscard attribute in C#

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");
}
like image 974
stefan Avatar asked Feb 28 '26 13:02

stefan


1 Answers

[[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.

like image 52
Mitch Avatar answered Mar 03 '26 02:03

Mitch