all groups > c# > may 2005 >
You're in the

c#

group:

Overriding == and testing to null



Overriding == and testing to null EL OSO
5/27/2005 11:29:15 PM
c#: Hi, let's suppose I have a

class A
{
int x;
...
public static bool operator == (A a1 , A a2)
{
return (a1.x==a2.x);
}
}

But, outside the class, I have a problem when I try to test a probably not
initialized class.
For instance, think about this code:
public void myFunc()
{
A a1;
A a2;
.....
if (a1 == null)
{
//some null value handling
}
....
}

The problem is that testing a1==null creates recursive calls to the operator
== of class A.
How do I test if something is null without having to invoke the == operator
for that "something"?


Tnx in advance.

Re: Overriding == and testing to null EL OSO
5/27/2005 11:39:29 PM
Dumb of me, I mixed two questions.
What I was trying to say is that the invoked operator == for class A creates
a null reference when it tries to access a2.x when a2 is null (as I wrote on
MyFunc)

I tried in the definition of operator == something like
if (a1==null) or (a2==null)
return false
else
return (a1.x == (a2.x)

BUT, comparing a1 == null creates the recursive call to operator == in class
A

Do I make myself more clear this time? :p





"EL OSO" <noone@nospam.com> escribió en el mensaje
news:OaE65zyYFHA.3280@TK2MSFTNGP09.phx.gbl...
[quoted text, click to view]

Re: Overriding == and testing to null Mattias Sjögren
5/28/2005 12:00:00 AM

[quoted text, click to view]

Cast to object first to prevent that.

if ( (object)a1 == null )



Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Re: Overriding == and testing to null Helge Jensen
5/28/2005 12:00:00 AM


[quoted text, click to view]

That's not really what you want, is it, if (object)a1 == null &&
(object)a2 == null ;)

I use the pattern:

public static bool operator==(A a1, A a2) {
if ( (object)a1 == null )
return (object)a2 == null;
else if ((object)a2 == null)
return false;
else
return a1.x == a2.x
}

[quoted text, click to view]

Yes, you just overloaded operator==(A,A), so that gets called to compare
a1 and null.

The "trick" is to make a1 staticly typed as something that compares by
reference with operator==: object.

[quoted text, click to view]

mostly,... I'm not that good at being clear myself.

--
Helge Jensen
mailto:helge.jensen@slog.dk
sip:helge.jensen@slog.dk
Re: Overriding == and testing to null Ted Miller
5/28/2005 10:55:24 AM
You could use object.ReferenceEquals().

[quoted text, click to view]

AddThis Social Bookmark Button