Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...