locked
Problem overrding == and checking for NULL.... RRS feed

  • Question

  • totally sbumbled here.

    I have some classes that I Want to override == for.

    THe problem is that in the == method, one of the two parts may be NULL when comparing with a variable in the form
    Class X
    X a = new X ();
    X b = null
    if (a == b)

    Now, this means within the == override I get a nullpointerexception . which I dont like.

    Sadly, I am totally unaware of a way to check whether one of the parameters is null now.

    public static bool operator == (InstrumentKey left, InstrumentKey right) {
      if (left == null) {

    results in a call to the overriden ==

    Is there another way to check for a null pointer? There seems to be no IsNull method. What is the recommended approach for these scenarios?
    Friday, October 30, 2009 8:54 AM

Answers

  • Instead of

        if (left == null) {

    use

        if (object.ReferenceEquals(left, null)) {
    • Proposed as answer by Matthew Watson Friday, October 30, 2009 10:11 AM
    • Marked as answer by JustTom Friday, October 30, 2009 12:18 PM
    Friday, October 30, 2009 10:10 AM

All replies

  • Hi,

    Actually If you compare object it always return false.
    Friday, October 30, 2009 9:24 AM
  • Instead of

        if (left == null) {

    use

        if (object.ReferenceEquals(left, null)) {
    • Proposed as answer by Matthew Watson Friday, October 30, 2009 10:11 AM
    • Marked as answer by JustTom Friday, October 30, 2009 12:18 PM
    Friday, October 30, 2009 10:10 AM
  • That was excatly it ;)
    Friday, October 30, 2009 12:18 PM