Roslyn: Inline temporary variable makes function return wrong value

Created on 21 Aug 2016  路  3Comments  路  Source: dotnet/roslyn

Version Used:
VS 2015 Update 3. (Framework 4.6.2)
Steps to Reproduce:

  1. Create this method:
public static string Repro()
    {
      var result = string.Empty;

      try
      {
        result = "foo";
      }
      catch (Exception)
      {
        result = "bar";
      }

      return result;
    }
  1. Apply 'Inline temporary variable' refactoring.
  2. Result:
public static string Repro()
    {
      var result = string.Empty;

      try
      {
        result = "foo";
      }
      catch (Exception)
      {
        result = "bar";
      }

      return string.Empty;
    }

Expected Behavior:
returns "foo"
Actual Behavior:
returns string.Empty

Area-IDE Bug Resolution-By Design

All 3 comments

Why would you expect it to return "foo"?

Inline Temporary replaces uses of the variable with it's initializer, which in this case is string.Empty. The fact that it doesn't eliminate the result or update the uses inside the try/catch is because it detects that those are conflicts (the expression being inlined is not an l-value). Note the red outlines around the assignments and the text "Conflict(s) detected" in the preview when invoking the refactoring.

I just wasn't expecting a refactoring to create bugs in my code. So in this particular case I would expect Roslyn not to even offer an option to inline the variable, because of the consequences.
Also, I have Resharper installed and it prevented the 'conflicts detected' window from showing up.

I guess interference from Resharper confused me and let me to believe this is a bug.

With Resharper disabled, everything looks fine. var result = string.Empty is not marked for refactoring, and pressing ctrl+. immediately shows conflicts.

This isn't a bug at all. Sorry for the confusion caused.

in this particular case I would expect Roslyn not to even offer an option to inline the variable

Our general philosophy is to allow you to do things even if they aren't perfect because it might be one step in a process you are doing and still helpful. We do try to include conflict information though, so that you can make an informed choice about whether or not to proceed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

glennblock picture glennblock  路  3Comments

vbcodec picture vbcodec  路  3Comments

joshua-mng picture joshua-mng  路  3Comments

NikChao picture NikChao  路  3Comments

AdamSpeight2008 picture AdamSpeight2008  路  3Comments