Operator Overloading with C# Extension Methods

Posted by Blinky on Stack Overflow See other posts from Stack Overflow or by Blinky
Published on 2008-10-05T20:59:03Z Indexed on 2010/04/23 21:23 UTC
Read the original article Hit count: 255

I'm attempting to use extension methods to add an operater overload to the C# StringBuilder class. Specifically, given StringBuilder sb, I'd like sb += "text" to become equivalent to sb.Append("text");

Here's the syntax for creating an extension method for StringBuilder:

public static class sbExtensions
{
    public static StringBuilder blah(this StringBuilder sb)
    {
        return sb;
    }
}

It successfully adds the "blah" extension method to the StringBuilder.

Unfortunately, operator overloading does not seem to work:

public static class sbExtensions
   {
        public static StringBuilder operator +(this StringBuilder sb, string s)
        {
            return sb.Append(s);
        }
    }

Among other issues, the keyword 'this' is not allowed in this context.

Are adding operator overloads via extension methods possible? If so, what's the proper way to go about it?

© Stack Overflow or respective owner

Related posts about c#

Related posts about extension-methods