ReSharper Wish List: Replace Literal With…

One thing I would love ReSharper to do for me is to replace a literal string with a local variable or constant and also refactor any other usings, optionally including internal usages, of the same string literal.

I would like for it to take:

public string Foo(IDictionary<string,string> d){
     if(d.ContainsKey("foo")){
         return d["foo"];
     }
     return string.Empty;
}

…and change it to:

public string Foo(IDictionary<string,string> d){
     string key = "foo";
     if(d.ContainsKey(key)){
         return d[key];
     }
     return string.Empty;
}

That sounds very doable to me, but maybe I’m not seeing the complexity. I know ReSharper has API’s for creating your own custom context actions, but I haven’t looked into that yet.

4 Comments so far

  1. Oleg Stepanov on August 11th, 2008

    We already have this functionality. You should select “Foo” and use “Introduce Variable” refactoring. It will do the rest :)

  2. mark on August 11th, 2008

    That’s great! It isn’t as discoverable as a context action, but pretty easy.

    Ctrl+R,F = Introduce Field
    Ctrl+R,V = Introduce Variable

    Be sure to Ctrl+w with the cursor in the string to extend the selection to the entire string.

  3. mark on August 11th, 2008
  4. Pages tagged "literal" on August 14th, 2008

    [...] bookmarks tagged literal ReSharper Wish List: Replace Literal With… saved by 2 others     sweetcandy202 bookmarked on 08/14/08 | [...]

Leave a Reply