473,387 Members | 1,516 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

compairing to null when operator is overridden

I'm having a difficulty compairing null to a class object whose "equal"
operator is overridden.. Consider the following:

class Foo
{
// ...
public static bool operator==(Foo f1, Foo f2)
{ return (f1.n == f2.n); }

Now the following throws:
Foo foo = new Foo();
if(null == foo) // throws System.NullReferenceException
{ //

If I check for null inside my operator override, it causes stack overflow.
public static bool operator==(Foo f1, Foo f2)
{
if(null == t1) ... // stack overflow

So my question is what's the correct way to handle null comparison when your
class overrides the equal operator?

Nov 17 '05 #1
8 2103
The correct way to override == is to first override .Equals and
..HashCode and then call .Equals method. You can check for null values
inside the .Equals method.

Your overloaded operator will look like :

public static bool operator==(Foo f1, Foo f2)
{ return (f1.Equals(f2)); }

and the .Equals method can look like :

public override bool Equals(object obj)
{
if (obj == null)
return false;
return ((Foo)obj).n.Equals(n);
}

Nov 17 '05 #2
Pesso <pe***@no.where> wrote:
I'm having a difficulty compairing null to a class object whose "equal"
operator is overridden.. Consider the following:

class Foo
{
// ...
public static bool operator==(Foo f1, Foo f2)
{ return (f1.n == f2.n); }

Now the following throws:
Foo foo = new Foo();
if(null == foo) // throws System.NullReferenceException
{ //

If I check for null inside my operator override, it causes stack overflow.
public static bool operator==(Foo f1, Foo f2)
{
if(null == t1) ... // stack overflow

So my question is what's the correct way to handle null comparison when your
class overrides the equal operator?


Either cast t1 to object first, or use object.ReferenceEquals.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3
On 10 Sep 2005 14:06:56 -0700, "Tasos Vogiatzoglou"
<tv*****@gmail.com> wrote:
The correct way to override == is to first override .Equals and
.HashCode and then call .Equals method. You can check for null values
inside the .Equals method.

Your overloaded operator will look like :

public static bool operator==(Foo f1, Foo f2)
{ return (f1.Equals(f2)); }


That's not quite enough, you must check f1 against null before
attempting to invoke a method on it. Add the following line before
the return:

if ((object) f1 == null) return ((object) f2 == null);

Additionally, your Object.Equals override won't get called by
operator== if the class also provides a strongly-typed overload of
Equals, and in such a strongly-typed overload you'll once again have
to use an object cast for the null check.
--
http://www.kynosarges.de
Nov 17 '05 #4
On Sat, 10 Sep 2005 22:09:41 +0100, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:
Either cast t1 to object first, or use object.ReferenceEquals.


Do you know the IL generated for ReferenceEquals? If it's a method
call you should use an object cast instead because ((object) x ==
null) gets compiled into optimal IL (a single null comparison opcode).
--
http://www.kynosarges.de
Nov 17 '05 #5
Christoph Nahr <ch************@kynosarges.de> wrote:
On Sat, 10 Sep 2005 22:09:41 +0100, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:
Either cast t1 to object first, or use object.ReferenceEquals.


Do you know the IL generated for ReferenceEquals? If it's a method
call you should use an object cast instead because ((object) x ==
null) gets compiled into optimal IL (a single null comparison opcode).


It will certainly be a method call in IL, but of course it may well be
inlined by the JIT. However, I wouldn't use that as the main criterion
at all - for me, it depends which you find most readable. Use the most
readable form until you've got good evidence that the code in question
is actually a bottleneck in your application.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6
On Sun, 11 Sep 2005 09:42:50 +0100, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:
It will certainly be a method call in IL, but of course it may well be
inlined by the JIT.
Good point, my mistake. Object.ReferenceEquals is a static method
that contains just the single line "return (x == y)" so it's certainly
going to be inlined, and the effect will be the same... at least when
optimization is turned on.
However, I wouldn't use that as the main criterion
at all - for me, it depends which you find most readable. Use the most
readable form until you've got good evidence that the code in question
is actually a bottleneck in your application.


Personally I don't see any difference in readability between the two
variants -- the operator== version would be more readable if you
didn't need the object cast, but since you do it's a wash.

In general, though, if there's one place where premature optimization
is a good idea it's in infrastructure methods such as equality tests.
These low-level methods are likely to show up at the end of a lot of
call trees, and so will have a broad influence on your application's
performance regardless of the presence of specific hotspots.

If you never pay any attention to performance before profiling you may
well end up with an application that's quite sluggish everywhere, but
does not have any bottlenecks that are detectable by profiling...
--
http://www.kynosarges.de
Nov 17 '05 #7
Christoph Nahr <ch************@kynosarges.de> wrote:
On Sun, 11 Sep 2005 09:42:50 +0100, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:
It will certainly be a method call in IL, but of course it may well be
inlined by the JIT.
Good point, my mistake. Object.ReferenceEquals is a static method
that contains just the single line "return (x == y)" so it's certainly
going to be inlined, and the effect will be the same... at least when
optimization is turned on.


Yup.
However, I wouldn't use that as the main criterion
at all - for me, it depends which you find most readable. Use the most
readable form until you've got good evidence that the code in question
is actually a bottleneck in your application.


Personally I don't see any difference in readability between the two
variants -- the operator== version would be more readable if you
didn't need the object cast, but since you do it's a wash.


It's very much a matter of taste. I don't find either particularly more
readable, but I think object.ReferenceEquals is perhaps a little more
explicit.
In general, though, if there's one place where premature optimization
is a good idea it's in infrastructure methods such as equality tests.
These low-level methods are likely to show up at the end of a lot of
call trees, and so will have a broad influence on your application's
performance regardless of the presence of specific hotspots.

If you never pay any attention to performance before profiling you may
well end up with an application that's quite sluggish everywhere, but
does not have any bottlenecks that are detectable by profiling...


You *may* do - but in my experience, you don't actually do so. Firstly,
it would depend on how often Equals was actually called - I don't find
myself calling Equals on my own types on a very regular basis.

Secondly, the architecture design is still more likely to be the
overwhelming factor, IMO. *That* is very hard to change later on,
whereas improving the performance of "leaf" methods like Equals is very
easy to do *if* you need to.

(Profiling *would* show this up to be a bottleneck if it genuinely was,
IMO - if you can see a significant portion of your time spent in Equals
methods, that should ring alarm bells.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
You are correct... I didn't thing the other situations... My mistake
....

Nov 17 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: user | last post by:
Hi, Is it possible to override assignment, the way that '+' can be overridden for example? Thanks, Toby
102
by: junky_fellow | last post by:
Can 0x0 be a valid virtual address in the address space of an application ? If it is valid, then the location pointed by a NULL pointer is also valid and application should not receive "SIGSEGV"...
3
by: Mark Oliver | last post by:
Hi, When I test my user defined class type passed parameter variable for null it throws an exception. If I use class "string" the null test doesn't through an exception. What could I be...
18
by: JohnR | last post by:
From reading the documentation, this should be a relatively easy thing. I have an arraylist of custom class instances which I want to search with an"indexof" where I'm passing an instance if the...
2
by: Tom Smith | last post by:
I'm having difficulty with overloading ==, and it's making my brain melt - can you help...? What I want to have is: 1) A base class A with virtual operator== defined (no problem) 2) A class B...
17
by: sonu | last post by:
Hi i want to find the greater number without any operator. so please any one help me and send some code Thanks Sonu
14
by: Hunk | last post by:
Hi I ws wondering if there is a way to implement operator+ in case of virtual classes. Here's the problem. I have to have a base string class from which two classes (normal char string and a...
0
by: Billy | last post by:
Is it possible to access the standard global new operator after it's been overridden? For instance, I have a situation like this void* operator new( size_t numBytes ) { return...
19
by: Michael C | last post by:
If we have something like this object x = null; MessageBox.Show(x.ToString()) we get an error. That kindof makes sense but there is no reason the behaviour couldn't be to return an empty...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.