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; } }
Mania source share