0

I have a code block that is implicitly adding variables to an array, i.e.

context.People.Add( new Person { Name = "Joe", Age = 45 }, new Person { Name = "Alicia", Age = 33 } );

What I need is for the variables to be accessible outside of the code block, i.e.

var personJoe = new Person { Name = "Joe", Age = 45 };
var personAlicia = new Person { Name = "Alicia", Age = 33 };
context.People.Add(personJoe, personAlicia);

This way I can access the person variables when I need to make an assignment to another entity that has a relationship with person.

My question is, what is the easiest way to perform this refactoring? I understand I can copy/paste, but the block I have is approximately 200 lines long, and I have found myself needing this type of re-factoring often. If at all possible, I would like to avoid paid solutions (ReSharper), but if this is the only way to get this process automated, I will seriously consider it.

Josh McKearin
  • 742
  • 4
  • 19
  • 42

2 Answers2

1

Seems to me this is simply an Introduce Variable refactoring. Visual Studio doesn't have this refactoring built in; but may other add-ons do. If you don't want a paid solution, then the refactoring consists of copy/paste then adding a variable and using it.

To do this in Resharper (with the Visual Studio keyboard scheme), simple select where you instantiate the Person (e.g. new Person { Name = "Alicia", Age = 33 }) and press Ctrl+R,V.

Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
  • Do you know which of the paid solutions actually offer this refactoring? I looked at Resharper's website, but it wasn't clear to me if they offer this as an option. – Josh McKearin Feb 22 '14 at 18:48
  • Resharper has it (http://www.jetbrains.com/resharper/webhelp/Refactorings__Introduce_Variable.html, or see edit) as well as CodeRush (Although they call it "Introduce Result Variable": https://documentation.devexpress.com/#CodeRush/CustomDocument2902 or Introduce Local: https://documentation.devexpress.com/CodeRush/CustomDocument1506.aspx) – Peter Ritchie Feb 22 '14 at 18:53
  • Telerik's JustCode has it as well: http://www.telerik.com/help/justcode/refactorings-introduce-variable.html – Peter Ritchie Feb 22 '14 at 18:56
  • This is what I was looking for. It would be nice to be able to do it en masse, but this will have to do. Thanks Peter – Josh McKearin Feb 22 '14 at 19:10
  • I had that same idea, Hadi Hariri added it as a suggestion for Resharper: http://youtrack.jetbrains.com/issue/RSRP-200132 – Peter Ritchie Feb 22 '14 at 19:37
1

I just wrote this CodeRush plugin. (It took about 20-30 minutes :) ) I think it does what you're looking for.

Introduce Local (All arguments)

If you've got CodeRush installed you can Download it here

Rory Becker
  • 15,551
  • 16
  • 69
  • 94