Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 402
Christian Gollhardt Avatar asked Apr 21 '16 00:04

Christian Gollhardt


People also ask

What happens if you don't return a value?

If you do not explicitly return a value, the caller will nonetheless use whatever garbage happens to be in that register. The compiler will also use all registers it has available for internal computation within the function.

What does it mean when a value is returned?

A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string.


1 Answers

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.

like image 141
Christian Gollhardt Avatar answered Sep 28 '22 02:09

Christian Gollhardt