Visual Studio C # – Can I extract a text to a string variable?

If I enter the same text string in multiple places in the program, is there any way to extract it into a string variable, and in each position I typed initially , Do you point the code to this variable?

For example, I have the following code:

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

I can refactor it to:

< /p>

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

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

I know this is what I should do at first, but let me say that I first get the logic of a program, and then I will sort out my code, whether in Visual Studio Is there any shortcut that allows me to do this or do I need to do it manually?

Thank you

If you use Resharper, you only need to select the first character String, press CTRL RV to introduce the variable. For the same string, it will ask you whether you want to replace both with the variable you introduced.

CTRL SHIFT R is another very important Good keyboard shortcuts, it will also display other refactoring options, such as importing parameters, fields, variables, etc.

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

If I enter the same text string in multiple places in the program, is there any way to extract it into a string variable, and type it at the beginning In each position, does the code point to this variable?

For example, I have the following code:

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

I can refactor it to:

< /p>

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

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

I know this is what I should do at first, but let me say that I first get the logic of a program, and then I will sort out my code, whether in Visual Studio Is there any shortcut that allows me to do this or do I need to do it manually?

Thank you

If you use Resharper, you only need to select the first string and press CTRL RV to introduce variables. For the same , It will ask you if you want to replace both with the variables you introduced.

CTRL SHIFT R is another good keyboard shortcut, it will also display other heavy Configuration options, such as introducing parameters, fields, variables, etc.

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

Leave a Comment

Your email address will not be published.