Search code examples
c#visual-studiovisual-studio-codestring-interpolation

Convert all strings in a class to interpolated strings


I want to convert all strings that have a variable in it, example:

string = "Hi " + name + ", How are you?"

to his interpolated version, refactoring all these cases in a class.

I tried several ways with visual studio and visual studio code, but no one has this function, maybe with regex i can achieve this.


Solution

  • Visual Studio can only do this for one instance at a time, as you have probably already discovered.

    However, Resharper has a function to do this for all occurrences.

    For the following code:

    public static void Main()
    {
        string name = "matthew";
    
        string s = "Hi " + name + ", How are you?";
        string t = "Hi " + name + ", How are you?";
    
        Console.WriteLine(s + t);
    }
    

    It provides something like this:

    Resharper refactoring options

    The options for "Method" and "Class" only appear if they are needed, so this screenshot was generated from slightly different code than shown above.