ReSharper User tip: Refactor magical strings to variable

Update! You can now find more user tips with the ReSharper user tip tag.

resharper-logoI've been using Jetbrains ReSharper a while now and I love it. I can't even imagine going back to plain Visual Studio anymore because there are so many things in my daily work that involves ReSharper, even simple tasks like editing source code and navigating through code and source files, let alone creating files and running unit tests.

Now I want to share a user tip I found that isn't obvious to find nor part of any context menu. It's actually a refactoring and I call it Magical strings to variable. You can use it when you end up with multiple equal string literals in a piece of code. You would probably want to gather all of the string literals in a variable and reuse it through out the code. You can use ReSharper to do it for you in a couple of key strokes.

Example

[Test]
public void ParentPresenter_Update_should_update_view() {
    var model = new User {
                        Name = "foo"
                    };
    using (mockery.Record()) {
        Expect.Call(parentView.Username = "foo");
    }
    using (mockery.Playback()) {
        IParentPresenter presenter = new ParentPresenter(parentView) {
                                Model = model
                            };
        presenter.Update();
        Assert.That(presenter.Model.Name, Is.EqualTo("foo"));
    }
}
arrow-down

[Test]
public void ParentPresenter_Update_should_update_view() {
    var name = "foo";
    var model = new User {
                        Name = name
                    };
    using (mockery.Record()) {
        Expect.Call(parentView.Username = name);
    }
    using (mockery.Playback()) {
        IParentPresenter presenter = 
            new ParentPresenter(parentView) {Model = model};
        presenter.Update();
        Assert.That(presenter.Model.Name, Is.EqualTo(name));
    }
}

Mechanics

1. Highlight one of the string literals

2. Press Ctrl+R, V (Ctrl+Alt+V)* to introduce a variable

3. Select to replace all occurrences (default option)

refactor magical strings introduce variable

4. Pick a name for the variable

refactor magical stringspick a name

..and you're done! Please leave a comment if you find this usefull.

* Visual Studio scheme (ReSharper 2.x / IDEA scheme)

Loading
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.