overloading == operator in c# fails checking for null values

Hi, I have developed one class called CProductInfo providing == and != operator features. I have one problem.

When I use this class in my program, say

CProductInfo product = null;

and later, when i check for emptiness,

if (product==null)

it returns false as if the product instance is not empty.

I tried various ways to eliminate this run-time error, but it just does not happen. Also I don't think there is use full tips on net for this.

Can someone help

Thanks in advance - Constantine

<<<< THE BRIEF SOURCE CODE FOR CProductInfo IS BELOW >>>>>

 


using System;
using System.Data;
using System.Data.SqlClient;
using MyDataLibrary;

namespace ProductManager2006
{
 public class CProductInfo:ConnectionManager
 {
  public string Title = "";
  public static bool operator == (CProductInfo product1, CProductInfo product2)
  {
   return product1.Equals(product2);
  }

  public static bool operator != (CProductInfo product1, CProductInfo product2)
  {
   return (!product1.Equals(product2));
  }

  public override bool Equals(object obj)
  {
   if (!(obj is CProductInfo)) return false;
   return this==(CProductInfo)obj;
  }

  public override int GetHashCode()
  {
   return base.GetHashCode ();
  }

  public override string ToString()
  {
   return base.ToString ();
  }

 }
}



Answer this question

overloading == operator in c# fails checking for null values

  • Ultrawhack

    You're really only supposed to override operator == for value types (e.g. structs).

    For reference types, you should be overriding the NON-STATIC "Equals()".


  • mnavkum

    >> This will also return false as there is no way to determine the values since they are unknown.

    That's just plain wrong. Try it in C#, and you'll see that (null == null) is true.

    What you say is true for SQL, but we are not talking about SQL here. We're discussing C#, and if null != null there, many things would come to a crashing halt. For example, the idiom:

    If (myObj != null)
    myString = myObj.Text;

    is used extensively throughout every C# program.



  • AsifHameed1

    >> This is where the problem comes, when I check, it always returns false.

    The change I suggested to the oper== would correct that problem.



  • Nadav Popplewell

    Hi Robert,
    I think you have a misunderstanding here. My problem is not to check the type of the product. Instead, I have to know whether the object is empty or not and depending on that I have to perform a set of operations.

    For e.g.

    CProductInfo product = null; //Declaration

    //codes

    //Somwhere in some other method

    if (product == null) //check whether the product is null
    {
    product = new CProductInfo(productId);

    //Statements
    }
    else
    {
    //Statements
    }

    So I am not testing the type of the product, but just want to know whether the object is null or not.

    if null, i want to post new transaction else update transaction.

    Thanks in Advance.


  • NessDan

    >> This will also return false as there is no way to determine the values since they are unknown.

    That's just plain wrong. Try it in C#, and you'll see that (null == null) is true.

    What you say is true for SQL, but we are talking about SQL here. We're discussing C#, and if null != null there, many things would come to a crashing halt. For example, the idiom:

    If (myObj != null)
    myString = myObj.Text;

    is used extensively throughout every C# program.



  • rt_ak1949

    The behavior you are describing is by design.

    Null actually means "Unknown Value" so in essence your product can never be equal to null. Even null is not equal to null.

    IOW, if you try

    If {null == null}

    This will also return false as there is no way to determine the values since they are unknown.

    Try checking the type of product instead to determine if it is a cProductInfo or not.

    Robert


  • FM_AX

    OOops... Meant to include this with my last message:

    Jon Skeet has written an article on the proper amount of code to include:

    See http://www.pobox.com/~skeet/csharp/http://www.pobox.com/~skeet/csharp/complete.html



  • Residual Logic Games

    Thanks buddy, it is true that I am supposed to overload for value types, however, i was able to solve my problem within next 10 minutes of my posting by type casting the parameter to object and compare it with null.

    So, the re-written chunk of code for == operator overloading for objects is as below.

    -------------------------------------- Re-Written CODE ----------------------------------------------

    public static bool operator == (CProductInfo product1, CProductInfo product2)

    {

    if (((object)product1)==null) return true;

    if (((object)product2)==null) return true;

    return product1.Equals(product2);

    }

    public static bool operator != (CProductInfo product1, CProductInfo product2)

    {

    if (((object)product1)==null) return false;

    if (((object)product2)==null) return false;

    return (!product1.Equals(product2));

    }

    public override bool Equals(object obj)

    {

    if (!(obj is CProductInfo)) return false;

    return this==(CProductInfo)obj;

    }

    Now i can do the following things

    CProductInfo p1 = null, p2 = null;

    if (p1==null)

    {

    bla bl abla

    }

    if (p1==p2)

    {

    bla bl abla
    }


  • Billr17

    I'm not sure what happened there with the paste --- it seemed to paste part of it twice.

    http://www.pobox.com/~skeet/csharp/complete.html



  • wpdehn

  • selva_kumar

    I think i got what you are trying to say.

    I am off my home for week end (friday is week end for us here). I will check it on sat and let you know.

    Just ignore my previous postings. Thanks.


  • Tonton888

    Hi buddy,

    as you've said, I changed the == operator functionality code to the following


    public static bool operator == (CProductInfo product1, CProductInfo product2)
    {
    if (Object.ReferenceEquals(product1, product2))
    return true; // if both the same object, or both null
    return product1.Equals(product2);
    }

    But this time, I received this exception while running.


    System.OutOfMemoryException: Error creating window handle. ---> System.NullReferenceException: Object reference not set to an instance of an object.


    This is what I want to achieve with this class.

    First, I declare a object

    CProductInfo product = null;

    then somewhere in the project, i need to check whether the memory is allocated for the object and if it is not allocated, based on that I need to allocate. e.g.

    if (product==null) product = new CProductInfo();


    Thanks in Advance


  • tonn

    Hi,

    My problem is not to compare the two objects.

    But I have to compare just two values of the properties, like <object1>.Title with <object2>.Title. Comparing the values are no problems, but the problem comes when I try to declare:

    CProductInfo product1 = null, product2 = null;

    Now, in another method, I want to assign product1.Title = some value. Before assigning I have to check whether the objects are not null. This is where the problem comes, when I check, it always returns false. e.g.

    if (product1==null)

    returns false, so it goes to wrong routing and tries to access the method Title, which in turn throws an exception that the object is not created.

    So, I want to solve this issue. I want to check for null and then the values (not the complete objects, just values of two methods as above in my code.)

    PS: Sorry for the complete code listing, was just in a hurry, so just pasted.

    I was able to overcome the problem by converting the CProductInfo parameter to object and then comparing with null. (I have mentioned it above). I just want to ensure this is perfect.

    Thanks in advance.


  • scyle

    First of all, this would be a whole bunch easier if you'd cut out the irrelevant parts before posting the code.

    The problem in in your Equals function:

    public override bool Equals(object obj)
    {
    if (!(obj is CProductInfo)) return false;
    return this==(CProductInfo)obj;
    }

    null is not a CProductInfo object, so it's going to return false, just like you told it to.

    TO get this to work, try changing your oper== to

    public static bool operator == (CProductInfo product1, CProductInfo product2)
    {
    if (Object.ReferenceEquals(product1, product2))
    return true; // if both the same object, or both null
    return product1.Equals(product2);
    }



  • overloading == operator in c# fails checking for null values