Hello, I have this problem:
class Person {
string name;
string surname;
public static bool operator ==(Person p1, Person p2)
{
if (p1.name == p2.name && p1.surname == p2.surname) return true;else return false;
}
}
//main program..
Person p = p.Mysearch("Tim"); // if it don't found Tim, Mysearch() return null
if (p == null) { ......} //problem is here
The problem is when I check for p ==null; I have defined == the check p.name and p.surname but null HASN'T any attribute (it isn't a person...
How can I solve it problem??
thanks.
Loading
AlanPosted Oct 31, 2007, 7:41 AM
If you recode that line as follows, then no exception will be thrown if p1 is null, whether you've overloaded the != operator or not:
if (p1 != null && p1.isNotProfessor()) listperson.Add(p1);
MarcoPosted Oct 30, 2007, 8:08 PM
if ( p1.isNotProfessor()) listperson.Add(p1);
Sometimes happen that p1 comes "null": so the code on the if crash at runtime.
Can I solve it ? thanks.
AlanPosted Oct 27, 2007, 6:21 PM
To avoid the == operator being called recursively, you need to use the static Object.ReferenceEquals() method to test for null.
You also need to override the != operator and, to get rid of the compiler wanrings that will otherwise come up, you should override the Object.Equals() and Object.GetHashCode() methods as well. Something like this:
public static bool operator ==(Person p1, Person p2)
{
if (Object.Equals(p1, null))
return (Object.ReferenceEquals(p2, null));
else if (Object.ReferenceEquals(p2,null))
return (Object.ReferenceEquals(p1,null));
else if (p1.name == p2.name && p1.surname == p2.surname)
return true;
else
return false;
}
public static bool operator !=(Person p1, Person p2)
{
return !(p1 == p2);
}
public override bool Equals(object obj)
{
if (!(obj is Person))
return false;
return (this == (Person)obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}