Implementing statements between null values ​​and base types - should I?

This is well known and discussed, but, to my surprise, I discovered today that you can give your own implementation of operators between NULL values ​​and their base types.

This means that you can have a struct that can be checked for null and return true .

Now it would be convenient in my situation - on the advice of another participant I have a structure that wraps strings. The ability to directly compare this wrapped string directly to null (rather than using .IsNull or similar) is much more natural to me, and means that switching from using strings to these WrappedStrings often does not require any other code changes.

But the fact that this function (I think) is little known contradicts the intuition of anyone who thinks about the structure (which is) above the line (which it represents), and that it confuses ReSharper ( structValue == null warns that " the expression is always false ") makes me think that this is possibly a dirty trick left in a dirty but tidy closet of tricks.

So I wonder if you would agree? If not, would you forgive me for this .. or is it really better not to go this route?


 public struct StringWrapper { private readonly string str; public override string ToString() { return str; } public static bool operator ==(StringWrapper a, StringWrapper b) { return a.str == b.str; } public static bool operator !=(StringWrapper a, StringWrapper b) { return !(a == b); } public static bool operator ==(StringWrapper a, StringWrapper? b) { if (!b.HasValue || b.Value.str == null) return a.str == null; return a == (StringWrapper)b; } public static bool operator !=(StringWrapper a, StringWrapper? b) { return !(a == b); } public static bool operator ==(StringWrapper? a, StringWrapper b) { return b == a; } public static bool operator !=(StringWrapper? a, StringWrapper b) { return !(a == b); } public StringWrapper(string str) { this.str = str; } } 
+6
source share
1 answer

I really believe in self-documenting code and adhere to the principle of least surprise . For example, getters should not modify data, etc. I would think that comparing a structural variable with zero confusion at first glance, so I would avoid it (no matter how convenient it is). This would be especially true if you would expect many people to use (or at least watch) their code.

+1
source

Source: https://habr.com/ru/post/897367/


All Articles