/// Tuesday, December 6

Object<T>

It's good practice to override Equals() and GetHashCode() in your classes. Well, that's what they say anyway, I rarely do. But, with generics and org.apache.commons.lang.builder.HashCodeBuilder (one of my java ports) it's easy to do. I created a generic base Object class:

public class Object<T> {
    public override int GetHashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    public bool Equals(T obj) {
        if (obj == null) {
            return false;
        }
        return obj.GetHashCode() == GetHashCode();
    }

    public override bool Equals(object obj) {
        if (obj == null) {
            return false;
        }

        if (obj is T) {
            return GetHashCode() == obj.GetHashCode();
        }
        else {
            return false;
        }
    }
}

HashCodeBuilder.reflectionHashCode(this) introspects all the fields of the class and creates a HashCode. To create a class with this functionality, derive from Object<T>:

public class Book : Object<Book> {
    string author = null;
    public string Title = null;
    public string Author {
        get { return author; }
        set { author = value;}
    }
}

This trick is great for unit testing where you need to compare the inner value of classes. Unfortunately you can seldom use this trick in C#, a single-inheritance language, unless you're building a framework and you derive from a single base. For performance, use HashCodeBuilder's append functions instead of reflection.

Comments:

lol ...very cool
 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?