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
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!