question

joshBAUER-1782 avatar image
0 Votes"
joshBAUER-1782 asked ·

c# operator overloading

I know that it is possible to overload operators in C# same as in c++.
In c++ I would do:
class string {
friend bool operator!=(const string& stString, const char* ndString);
};
bool operator!=(const string& stString, const char* ndString) {
return !(stString==ndString);
}
How to do this in C#?
I do:
class ww {
static public string operator +(string stString, string ndString) {
return "kk";
};
}
I got errors.


dotnet-csharp
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

SimpleSamples avatar image
0 Votes"
SimpleSamples answered ·
 public class ww
 {
 public static bool operator != (ww stString, ww ndString)
 {
 return !(stString == ndString);
 }
 }


· 4 ·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Just one observation: In C# when you redefine operator != you are required to also redefine operator == (and ideally, although the compiler cannot check it, you should make them consistent so that == returns the opposite of != ).

Also, if you are doing this with your own class instead of String, you should also override the method Equals so that it is consistent with operator ==. And when you override Equals, you should also override GetHashCode in such a way that two objects that are equal return the sane hash code.

And note the I said "your own class". In C# the compiler will not allow you to do it on "class string" like you are doing in C++.

0 Votes 0 ·

one of parameters must be "including type".
That is error given by compiler.

How to fix it?

0 Votes 0 ·

Not working for me in c#.

one of parameters must be "including type".
That is error given by compiler.

How to fix it?

0 Votes 0 ·

Sorry. I fixed the sample code. They type in the overload must match the type of its class.

0 Votes 0 ·