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?
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With