Overloading problems

G

Guest

Hi,

For some important reasons I've implemented a new type as
a class instead of a struct.

The type is called NKTd and I've overloaded the ==
operator as follows

public static bool operator==( NKTd a, NKTd b )
{
return ( a.value == b.value );
}

Now, if x is a NKTd (or pointer to) and I want to
evaluate something like:

if ( x == null)
{
....
}

The above will invoke the == overloaded code, and I'll
get a runtime error.
Is there a way to 'override' the left side to force it to
look at the reference.

I've tried 'if ( (object)x == null)' and it works fine,
but not very elegant to my opinion.


best regards
 
Z

Zürcher See

public static bool operator==( NKTd a, NKTd b )
{
if (a!=null && b!=null) return ( a.value == b.value );
return (object)a==(object)b;
}

Theoretic == is used to know if the two "pointers" point to the same object
If you want to know if two different objects are similar is better to use
(implements) .equals( .. )
 
N

Nicholas Paldino [.NET/C# MVP]

I would use the cast to object, because in essence, that is what you
want to do. You can also make a call to the static ReferenceEquals method
on the Object class, instead of performing the cast.

Also, on a side note, you should override GetHashCode as well, since you
overrode the Equals method (you overloaded the Equals operator, which means
you should have overridden the Equals method as well).

Hope this helps.
 
K

Kalpesh Shah

public static bool operator==(NKTD p, NKTD z)
{
object tmp = (object)z;
if (tmp == null)
return false;

return (p.Value == z.Value);
}


In one or the other way, one will have to cast it to object, otherwise it will result into
StackOverFlowException, if I use the following code

public static bool operator==(NKTD p, NKTD z)
{
if (tmp == null)
return false;

return (p.Value == z.Value);
}


HTH
Kalpesh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top