C# String Operator Overloading

String is a sealed class. You cannot inherit from it, and without the original source for String, you cannot compile a partial class of it. Even if you got your hands on the source (it's possible via Reflector or via Visual Studio symbol download) you'd still have problems, since it's a first class citizen in the runtime.

Do you really need < and > as operators on string? If so... why not just use extension methods?

public static bool IsLessThan(this string a, string b) 
{ 
    return a.CompareTo(b) < 0; 
} 

public static bool IsGreaterThan(this string a, string b) 
{ 
    return a.CompareTo(b) > 0; 
}


// elsewhere...
foo.IsLessThan(bar); // equivalent to foo < bar

There is no way to replace any built-in behaviour of the compiler with your own. You cannot override existing built-in operators for comparisons, conversions, arithmetic, and so on. That's by design; it's so that someone can read your code and know that int x = M(); int y = x + 2; does integer arithmetic, as opposed to, say, formatting your hard disk.

Can you explain why you want to do this? Perhaps there is a better way to do what you want.


The simple answer is that you can't; there's no way to modify the operators for another class. Partial classes are only allowed for classes that are both declared partial in all files and defined in the same assembly.