Hope the null conditional (?.) operator can check whether the target has overloaded != and == operators #9382
-
https://www.reddit.com/r/csharp/comments/8p5cab/null_conditional_operator_for_overloaded_and/ public class Test
{
int x = 1;
public static bool operator ==(Test lhs, Test rhs)
{
if(ReferenceEquals(lhs, rhs)) return true;
if(ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null)) return false;
return lhs.x == rhs.x;
}
public static bool operator!=(Test lhs, Test rhs)
{
if (ReferenceEquals(lhs, rhs)) return false;
if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null)) return true;
return lhs.x != rhs.x;
}
public void Show()
{
Console.WriteLine($"x={x}");
}
}
public class Program
{
static void Main(string[] args)
{
Test testA = new Test();
bool val = testA != null;
Console.WriteLine($"A != null: {val}");
testA?.Show();
}
} Like the code above, for common sense, |
Beta Was this translation helpful? Give feedback.
Answered by
CyrusNajmabadi
May 12, 2025
Replies: 1 comment 1 reply
-
No. This is intentional. This is specifically about behavior when the value is exactly null, and thus could not be the receiver value for a method call. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
CyrusNajmabadi
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No. This is intentional. This is specifically about behavior when the value is exactly null, and thus could not be the receiver value for a method call.