Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use less than on Strings?

Tags:

c#

.net

Using a string.CompareTo(string) i can get around this slightly but is not easy to read and i have read on that locallity settings might influence the result.

Is there a way to just simply use < or > on 2 Strings in a more straightforward way?

like image 607
Andy Avatar asked Oct 21 '25 04:10

Andy


2 Answers

You can overload operators but you seldom should. To me "stringA" > "stringB" wouldn't mean a damn thing, it's not helping readability IMO. That's why operator overloading guidelines advise not to overload operators if the meaning is not obvious.

EDIT: Operator Overloading Usage Guidelines

Also, in case of String I'm afraid you can't do it seeing as you can put operator-overloading methods only in the class in which the methods are defined. If the syntax of CompareTo bothers you, maybe wrapping it in extension method will solve your problem?

Like that:

public static bool IsLessThan(this string str, string str2) {
    return str.Compare(str2) < 0;
}

I still find it confusing for reader though. The bottom line is, you can't overload operators for String. Usually you can do something like declaring a partial and stuffing your overloads there, but String is a sealed class, so not this time. I think that the extension method with reasonable name is your best bet. You can put CompareTo or some custom logic inside it.

like image 185
Dyppl Avatar answered Oct 22 '25 19:10

Dyppl


CompareTo is the proper way in my opinion, you can use the overloads to specify culture specific parameters...

like image 33
Davide Piras Avatar answered Oct 22 '25 17:10

Davide Piras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!