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

大兔子大兔子 提交于 2019-12-06 19:16:47

问题


I have a extension method, which returns a value. In this case it should set a specific bit in an 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 can not combine this and ref:

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

It is easy to forget the assignment by accident. Someone can think, the method changes the value direct.

For a String.Replace, Resharper?/VisualStudio? is warning me, that the Return value of pure method is not used:

Is this also possible for my method in some way?


回答1:


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



来源:https://stackoverflow.com/questions/36757545/is-it-possible-to-get-a-warning-if-return-value-is-not-used

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!