Search code examples
c#resharpercode-inspection

Using ReSharper can you select a rule to ensure that the returned value is either a literal or a variable for C#


This question is about if ReSharper supports such a thing and how to turn such a rule check on. This is not a question about a particular coding style or standard choice or merit.

I am trying to automate checking for (and ideally replacement) of various C# return code patterns. In particular I wish to detect the following and have resharper make a hint/suggestion

return SomeFunc(someArgs);
return condition ? litteralA : litteralB;
return someObject.SomeFunction();

The following do not need to be highlighted (but I would accept them being picked up as innocent bystanders)

return someObject.SomePropertyOrField;

The following must not be falsely detected/highlighted (ideally ReSharper would do the simple transformation if possible)

var someVal = SomeFunc(someArgs);
return someVal;

var result = condition ? litteralA : litteralB;
return result;

var state = someObject.SomeFunction();
return state;

return SomeClass.SomeConst;
return true;
return 0;
return LocalConst;

Can the latest release of ReSharper do this and if so how can I configure it to do it

I cannot see how I would do it from the feature list or by looking through the inspection options of a trial version of ReSharper; but I don't know what such a rule would be called if it was in fact there. If it is in fact possible then I would like to know before having to write my code inspection utility.


Solution

  • I'm not going to go into why you want this; I'm sure you have a reason (which would be awesome if you share with the rest of us), but here's one solution:

    You can use Custom Patterns (Options | Code Inspection | Custom Patterns) like this:

    ReSharper Custom Patterns

    See more information here: ReSharper - Structural Search and Replace