Re: Comparison to null

Tech-Archive recommends: Speed Up your PC by fixing your registry

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 03/15/05


Date: Tue, 15 Mar 2005 17:51:14 -0000

Marcin Grz?bski <mgrzebski@taxussi.no.com.spam.pl> wrote:
> I think that a "key" is operator overloading.
> Like a Jon post it before.
>
> MyClass myVar;
>
> if( null==myVar ) {
> }
> Doesn't have a chance to fire MyClass "==" operator function.

Yes it does. Compile and run the following, ignoring the warnings:

using System;
using System.Data;

class Test
{
    static void Main()
    {
        Test t = new Test();
        Console.WriteLine (t==null);
        Console.WriteLine (null==t);
    }

    public static bool operator == (Test t1, Test t2)
    {
        Console.WriteLine ("Operator== called");
        Console.WriteLine ("t1={0}", t1);
        Console.WriteLine ("t2={0}", t2);
        return true;
    }
    
    public static bool operator!= (Test t1, Test t2)
    {
        return false;
    }
}

The output is:
Operator== called
t1=Test
t2=
True
Operator== called
t1=
t2=Test
True

In other words, the overloaded operator is called both times.

-- 
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Relevant Pages

  • RE: Redhat 9.0 development environment wierdness...
    ... It still has the warnings you posted. ... setup depends on you or the project you are trying to compile. ... Redhat 9.0 development environment wierdness... ... need to install on our servers and if I can't even get through these I ...
    (RedHat)
  • Re: does VS C++ 2005 actually work????
    ... may be the same size as a pointer, they have nothing logically to do with ... sizeofand size_t generating warnings when used in the context of API ... I can't compile ... justified criticism regarding the reliability of Windows. ...
    (microsoft.public.vc.mfc)
  • Re: 2.6.23.9-rt13
    ... If I compile -rt13 I get some compile warnings on ARM: ... Both warnings are fixed by the attached patch, but warning 2 needs some review. ... New changes by Steven Rostedt, Gregory Haskins, ... Revert lazy disable irq from simple irq handler ...
    (Linux-Kernel)
  • Re: Using unused variables
    ... I get loads of "unused variable" warnings during compile ... Compiler switches that disable reporting of unused variables are out of ... which may draw dead code diagnostics from aggressive optimizing compilers. ...
    (comp.lang.fortran)
  • Re: <ftream> errors under g++ 3.2.2
    ... > gives error messages about implicit typenames being deprecated, ... is nothing you can do to your code to prevent the warnings. ... From your output, I don't see compile failures, I see warnings. ... I am surprised that a GCC header would have an implicit ...
    (freebsd-current)