ReSharper quick-fix 'Use object initializer' action produces code that does not compile

Answered

VS2015

R# 2016.3.1

Hello,

Here is a small fragment of code (simplified for clarity).  It is taking a copy of an existing byte buffer and setting the value of the last byte within the copy to a specific value.

var bufferCopy = new List<byte>(buffer);
bufferCopy[bufferCopy.Count - 1] = 40;

ReSharper places a green zigzag line under the word 'new' and suggests the use of an object initialiser ('Use object initializer').

If I accept the suggestion, ReSharper changes the code to this:

var bufferCopy = new List<byte>(buffer) {[bufferCopy.Count - 1] = 40};

The changed code does not compile.  The fragment 'bufferCopy.Count - 1' is underlined in red and the following errors are shown:

  • Cannot use local variable 'bufferCopy' before it is declared
  • Operator '-' cannot be applied to operands of type 'method group' and 'int'

I don't think that the use of an initialiser is possible in this case and ReSharper should not be suggesting it.

2 comments
Comment actions Permalink
Official comment

Hello David

You are welcome to comment and follow https://youtrack.jetbrains.com/issue/RSRP-462632 request.

Thanks! 

Comment actions Permalink

Great!  I didn't really think that I was the first to come across this. :-)

0

Please sign in to leave a comment.