Sometimes a struct comes in handy, as it is a value type that cannot be NULL. You can't however write things like
a == b on them; that is unless you actualy define what == means for that struct. Take the following struct:
public struct IdName {
public int Id { get; set; }
public string Name { get; set; }
}
I simply tell it what == means, but watch out for null's. The compiler will also require that you define !=:
public static bool operator ==(IdName a, IdName b) {
if ((object)a == null && (object)b == null) return true;
else if ((object)a != null && (object)b != null) return a.Id == b.Id && a.Name == b.Name;
else return false;
}
public static bool operator !=(IdName a, IdName b) {
return !(a == b);
}
Compiling that will give you two warnings: you did not override
GetHashCode() nor
Equals(). These are necessary to get the underlying infrastructure to work well with the new type. So, implementing the latter should be easy:
public override bool Equals(object obj) {
if (obj != null && obj is IdName)
return ((IdName)obj).Id == Id && ((IdName)obj).Name == Name;
else
return false;
}
And the hashcode thing:
public override int GetHashCode() {
return base.GetHashCode() ^ Id;
}
And now you can write
a == b on structs, just like you can with integers and such.
No comments:
Post a Comment