Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying string instance variable with extension method

I'm trying to make a simple extension method, for the String class, which will allow me to supply text to be appended to an existing string variable with a newline character included:

string myStr = "Line 1";
myStr.AppendLine("Line 2");

This code should yield a string that prints as follows

Line 1
Line 2

Here's the code I wrote for it:

public static class StringExtensions
{
    public static void appendLine(this String str, string text)
    {
        str = str + text + Environment.NewLine;
    }
}

But when I call the code, the new text never gets appended to the original instance variable. How to achieve that?

like image 652
Jason O Avatar asked Sep 20 '26 17:09

Jason O


2 Answers

You need to modify value of variable for this to work as strings are immutable (see public C# string replace does not work). Unfortunately there is no way to do it with extension method as ref is not allowed there:

 public static void appendLine(this ref String str, string text) // invalid

So the your options

  • regular method with ref

      public static void AppendLine(ref String str, string text)
      {
         str = str + text;
      }
    
  • return new value from extension method:

      public static string AppendLine(this String str, string text)
      {
         return str + text;
      }
    

Note: consider if StringBuilder works better for your case.

like image 173
Alexei Levenkov Avatar answered Sep 22 '26 06:09

Alexei Levenkov


A string is immutable. Your extension method creates a new string rather than alter the one passed in. You'd need to write it as:

public static String AppendLine(this String str, string text)
{
    return str + text + Environment.NewLine;
}

And call it like this:

string myStr = "Line 1";
myStr = myStr.AppendLine("Line 2");
like image 25
Sean Avatar answered Sep 22 '26 07:09

Sean