473,715 Members | 6,112 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.NullRefe renceException
{ //

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 2120
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.Eq uals(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.NullRefe renceException
{ //

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.Referenc eEquals.

--
Jon Skeet - <sk***@pobox.co m>
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.co m> wrote:
Either cast t1 to object first, or use object.Referenc eEquals.


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.co m> wrote:
Either cast t1 to object first, or use object.Referenc eEquals.


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.co m>
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.co m> 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.Referenc eEquals 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.co m> 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.Referenc eEquals 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.Referenc eEquals 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.co m>
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
14393
by: user | last post by:
Hi, Is it possible to override assignment, the way that '+' can be overridden for example? Thanks, Toby
102
6011
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" ( i am talking of unix machine ) while trying to read that location. Then how can i distinguish between a NULL pointer and an invalid location ? Is this essential that NULL pointer should not point to any of the location in the virtual address...
3
1626
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 doing in my class that causes the exception? Thanks, Mark
18
4740
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 class where only the "searched" property has a value. I expected to get the index into the arraylist where I could then get the entire class instance. However, the 'indexof' is never calling my overloaded, overrides Equals method. Here is the...
2
7394
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 derived from A with operator== overridden (again, no problem) 3) Pointers A* b1, b2 which may actually point to instances of B, where I can call (*b1)==(*b2) and have it use the overridden form of == found in B. Having written this all out I'm...
17
2036
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
2335
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 hash string class ) are derived. The two derived classes are template classes specifying the sizes. The base class is a non-template class so that it can be used generically in the interface classes. the design would look like
0
1113
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 sDefaultHeap->Allocate( numBytes ); } Heap::Heap( unsigned int memSize ) {
19
2716
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 string. When we call x.ToString we are really calling a function like this: class Object
0
8718
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9343
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9104
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9047
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7973
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6646
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5967
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4477
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3175
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.