Is it possible define an extension operator method?

No, you can't have an extension method which is also an operator. Extension methods can only be declared in static classes, which can't have instances and according to the C# spec,

User-defined operator declarations always require at least one of the parameters to be of the class or struct type that contains the operator declaration. [7.3.2]

Therefore, it is impossible for an extension method to also be an overloaded operator.

Additionally, you can't override System.String since it is a sealed class.


No, it is not possible to do from outside of the class. ++ operator should be defined inside class which is being incremented. You can either create your own class which will be convertible from string and will have ++ overload or you can forget about this idea and use regular methods.


That is not possible in C#, but why not a standard extension method?

 public static class StringExtensions {
     public static string Increment(this string s) {
          ....
     }
 }

I think somestring.Increment() is even more readable, as you're not confusing people who really dont expect to see ++ applied to a string.


A clear example of where this would be useful is to be able to extend the TimeSpan class to include * and / operators.

This is what would ideally work...

public static class TimeSpanHelper
{
    public static TimeSpan operator *(TimeSpan span, double factor)
    {
        return TimeSpan.FromMilliseconds(span.TotalMilliseconds * factor);
    }

    public static TimeSpan operator *(double factor, TimeSpan span)  // * is commutative
    {
        return TimeSpan.FromMilliseconds(span.TotalMilliseconds * factor);
    }

    public static TimeSpan operator /(TimeSpan span, double sections)
    {
        return TimeSpan.FromMilliseconds(span.TotalMilliseconds / factor);
    }

    public static double operator /(TimeSpan span, TimeSpan period)
    {
        return span.TotalMilliseconds / period.TotalMilliseconds);
    }

}