The previous answers still seem to be correct, this is not implemented in C#. You can, however, get very close with a little more code.
Option 1, wrapper class around StringBuilder
Something like this:
public static class ExtStringBuilder
{
public class WStringBuilder
{
private StringBuilder _sb { get; }
public WStringBuilder(StringBuilder sb) => _sb = sb;
public static implicit operator StringBuilder(WStringBuilder sbw) => sbw._sb;
public static implicit operator WStringBuilder(StringBuilder sb) => new WStringBuilder(sb);
public static WStringBuilder operator +(WStringBuilder sbw, string s) => sbw._sb.Append(s);
}
public static WStringBuilder wrap(this StringBuilder sb) => sb;
}
usage like this:
StringBuilder sb = new StringBuilder();
// requires a method call which is inconvenient
sb = sb.wrap() + "string1" + "string2";
Or:
WStringBuilder sbw = new StringBuilder();
sbw = sbw + "string1" + "string2";
// you can pass sbw as a StringBuilder parameter
methodAcceptsStringBuilder(sbw);
// but you cannot call methods on it
// this fails: sbw.Append("string3");
You can make a wrapper for string
instead of StringBuilder
in the exact same fashion, which might be a better fit, but in this case, you'll be wrapping possibly many string
objects instead of 1 StringBuilder
object.
As another answer points out, this strategy seems to defeat a lot of the purpose of having an operator since depending on the use case, the way you use it changes. So it feels a little awkward.
In this case, I agree, this is far too much overhead just to replace a method like StringBuilder
's Append
method. However, if you are putting something more complicated behind the operator (something requiring a for loop, for instance), you may find this is a convenient solution for your project.