Bugzilla – Bug 323401
[GMCS] operator == on struct and null causes error
Last modified: 2007-09-15 21:24:23 UTC
---- Reported by marek.sieradzki@gmail.com 2007-02-03 13:07:57 MST ---- Description of Problem: Comparison between a struct (not nullable) and null causes compilation error. Steps to reproduce the problem: 1. Compile attached test case. Actual Results: struct.cs(18,22): error CS0019: Operator `==' cannot be applied to operands of type `A' and `null' Expected Results: Compilation succeeded (not really sure because it's such a weird case) How often does this happen? Always Additional Information: Compiled code prints 'false' with CSC 2.0 ---- Additional Comments From marek.sieradzki@gmail.com 2007-02-03 13:08:39 MST ---- Created an attachment (id=171388) test case (.cs) ---- Additional Comments From miguel@ximian.com 2007-02-14 14:57:47 MST ---- This seems to be a bug in csc, not a bug in mcs. CSC 1 reports that error correctly, we went through this recently. CSC 2 will basically generate a constant for that compare (as structs can never be null) and hide real bugs in your code. So I would say this is not a bug. ---- Additional Comments From gert.driesen@pandora.be 2007-02-14 15:18:51 MST ---- I've reported this issue to MS using the connect web site: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx? FeedbackID=257924 We'll see what MS responds on this. ---- Additional Comments From jonpryor@vt.edu 2007-04-17 11:52:48 MST ---- Microsoft's Response: The difference between the 1.1 compiler and the 2.0 compiler here is actually due to a change in the spec which makes the code you provided legal. This is related to the new C#2.0 feature "Nullable value types". Any operator between struct types, including ==, can now be 'lifted' to apply to the nullable version of the types. In your case, the == operator from a pair of As to bool can be lifted to an operator from a pair of "A?"s to bool. The left hand argument is implicitly converted from A to A? and the right hand "null" is convertible to A? be default. The specific operation in your code will always return "false" though. ---- Additional Comments From miguel@ximian.com 2007-07-23 13:17:35 MST ---- I think the explanation from Microsoft is incomplete, because in the particular case of: class Foo<T> where T: struct { bool IsNull (T x) { return x == null; } } Is not permitted. If you remove "struct" then the above code compiles with CSC. Imported an attachment (id=171388) Unknown operating system unknown. Setting to default OS "Other".