JMK
JMK

Reputation: 28059

Visual Studio C# - Can I extract a piece of text to a string variable?

If I have the same string of text typed at numerous locations in my program, is there any way I can extract this to a string variable and, at each location where this was originally typed, have the code instead point to this one variable?

For example, I have the following code:

if(File.Exists("C:\\whatever.txt"))
{
    File.Delete("C:\\whatever.txt");
}

Can I refactor that into this:

string s1 = "C:\\whatever.txt";

if(File.Exists(s1))
{
    File.Delete(s1);
}

I know this is what I should have done initially, but lets say I'm getting the logic of a program sorted first, then I come along after to tidy up my code, are there any shortcuts in Visual Studio to allow me to do this or would I need to do so manually?

Thanks

Upvotes: 3

Views: 1867

Answers (5)

Allrameest
Allrameest

Reputation: 4492

If you use Resharper, you can just select the first string, press CTRL+R+V to introduce a variable. For identical strings, it will ask you if you want both to be replaced by the variable you introduce.

CTRL+SHIFT+R is another good keyboard shortcut which also shows you other refactoring options like introduce parameter, field, variable etc.

If you use Visual Studio you really should have Resharper imo!

Upvotes: 5

SkeetJon
SkeetJon

Reputation: 1491

Resharper is a really good tool for this kind of thing. It's a visual studio plugin available here http://www.jetbrains.com/resharper/

Once installed you can use Ctrl+Shift+R to remove magic strings like this. You could also use the visual studio Find and Replace function.

Upvotes: 2

Lloyd
Lloyd

Reputation: 2942

Arguably it might be best to do it manually, unless you have Resharper, also be weary of the differences in String Literals and how they can effect your code.

Upvotes: 1

Cristian Lupascu
Cristian Lupascu

Reputation: 40546

I don't think there's a feature like that in Visual Studio, but Resharper has it: it's called the Extract Variable refactoring. I'm really used to its keyboard shortcut (CTRL+R, CTRL+V).

A nice thing about it is that it asks whether to replace all occurences of the string, or just the selected one.

Upvotes: 3

Mharlin
Mharlin

Reputation: 1705

You need to do it manually. If you use the same path in many places in your application you can also store it in you configuration file.

Upvotes: 1

Related Questions