Christian Gollhardt
Christian Gollhardt

Reputation: 17034

Is it possible to get a warning if return value is not used?

I have an extension method which returns a value. In this case, it should set a specific bit in a byte:

public static byte SetBit(this byte b, int bitNumber, bool value)
{
    if (value)
    {
        return (byte)(b | (1 << bitNumber));
    }
    return (byte)(b & ~(1 << bitNumber));
}

The returned value needs to be assigned to a variable again, because I cannot combine this and ref:

byte myByte = 3;
myByte = myByte.SetBit(1, false);

It is easy to forget the assignment by accident. Someone might think that the method changes the value directly.

For a String.Replace, ReSharper/Visual Studio(?) is warning me that the Return value of pure method is not used:

String

Is this also possible for my method in some way?

Upvotes: 24

Views: 4894

Answers (3)

Myk
Myk

Reputation: 1608

As others have pointed out if being notified about unused returned values from every method, you can either use the Remove unnecessary expression value MS code analysis rule or the analyzers from CSharpExtensions

If you prefer to get a warning only when the return value of explicitly specified methods is ignored, consider checking out my MustUseRetVal analyzer.

It emits a diagnostic if it comes across code that ignores the value returned from a method marked with [MustUseReturnValue]

For example

[MustUseReturnValue]
public bool IsGrantedDatabaseWritePermission() {
   // ...
}

// Elsewhere in your code:
// The value returned from `IsGrantedDatabaseWritePermission` must be
// assigned to a variable or checked in an if statement, etc.
// Otherwise, the analyzer will emit an error.
var isGranted = IsGrantedDatabaseWritePermission();
if (isGranted)
    WriteToDatabase();

Upvotes: 1

Andrew D. Bond
Andrew D. Bond

Reputation: 1300

If you're open to being notified in general about return values being unused and not explicitly discarded, you can use the Microsoft code analysis rule https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0058

Upvotes: 2

Christian Gollhardt
Christian Gollhardt

Reputation: 17034

Update:

Now there is a PureAttribute in the System.Diagnostics.Contracts namespace.

[Pure]
public byte Foo()
{
    //...
}

Pre .NET Standard 2.0 Answer:

There seems to be a Nuget Package for ReSharper Annotations.

This includes a MustUseReturnValueAttribute:

[MustUseReturnValue("Use the return value to...")]
public byte Foo()
{    
}

As @Kirk Woll pointed out in the comments, it is also possible to write a custom Roslyn Analyzer.

Upvotes: 17

Related Questions