KoenV

January 2008 - Posts

Operator overloading and testing for null

Operator overloading in C# is basically writing a public static method, like this:

public static bool operator ==(CustomObject object1, CustomObject object2)
{
    return object1.SomeProperty == object2.SomeProperty;
}

Before you do this, it is necessary to check if both parameters are not null, otherwise you will get a NullReferenceException when doing this:

CustomObject object1 = GetCustomObject();
if (object1 == null)

But you cannot do the following because it will simply recurse the evaluation to the same method, and give you a StackOverflowException:

public static bool operator ==(CustomObject object1, CustomObject object2)
{
    if (object1 == null || object2 == null)
    {
        //...

Instead you can cast your parameters to "object"s before evaluating, which will use the == operator for Object:

if ((object)object1 == null || (object)object2 == null)

Also, if you don't want to repeat the whole bunch again for the != operator, you can simply write this:

public static bool operator !=(CustomObject object1, CustomObject object2)
{
    return !(object1 == object2);
}

Posted: Jan 25 2008, 12:54 AM by koevoeter | with 1 comment(s)
Filed under:
Kick-off post

I've been having this idea about a blog for a while now. Basically because I often run into a problem that I had before but then it's still hard to figure out how I fixed it back then. Now this will be my little public howto-database.

I'll try to post several bits a week about various topics of software development, but mainly about web development, ASP.NET, scripting,...

Thanks to Joe and the rest of the www.asp.net team for opening up some space for us...

Posted: Jan 25 2008, 12:26 AM by koevoeter | with no comments
Filed under:
More Posts