Can I make method return values non-discardable in C#

Viewed 42

Example

I have a static method like this:

public static MyClass CreateMyClass()
{
  return new MyClass()
  {
    Foo = "SomeVal",
    Bar = 123
  };
}

Now it occurred, that this function was called like this.

public class ConsumerClass
{
  public ConsumerClass
  {
    CreatePluginUpdateProcess();
    // oopsie, should have been
    // myClass = CreatePluginUpdateProcess();
  }

  private MyClass myClass;
}

Question

How can I cause this code to emit a warning, or an error. What I am looking for is an attribute that I can mark my CreateMyClass() method with, so that the Compiler will warn when the return value is ignored.

Alternative phrasing of question

In C++ there is the [[nodiscard]] attribute. Which causes a warning when ignoring the return value of a function marked with [[nodiscard]].

So an alternative way to phrase this question is: What is the C# equivalent of the C++ [[nodiscard]] attribute.

0 Answers
Related