views:

161

answers:

3

I've looked for overriding guidelines for structs, but all I can find is for classes.

At first I thought I wouldn't have to check to see if the passed object was null, as structs are value types and can't be null. But now that I come to think of it, as equals signature is

public bool Equals(object obj)

it seems there is nothing preventing the user of my struct to be trying to compare it with an arbitrary reference type.

My second point concerns the casting I (think I) have to make before I compare my private fields in my struct. How am I supposed to cast the object to my struct's type? C#'s as keyword seems only suitable for reference types.

Thanks

+2  A: 

Use the is operator:

public bool Equals(object obj)
{
  if (obj is MyStruct)
  {
    var o = (MyStruct)obj;
    ...
  }
}
Dan Story
+6  A: 
struct MyStruct 
{
   public bool Equals(object obj) 
   {
       if (!(obj is MyStruct))
          return false;

       MyStruct mys = (MyStruct) obj;
       // compare elements here

   }

}
James Curran
+1  A: 

Adding to the existing answers.

You can still have nullable values if you append a ? after the struct name (this works for every value object)

int?

Casting is done also by calling (MyStructName)variableName

jpabluz
You can, but nullables have a very high performance penalty that will more than cost any benefit you would have gained by using "as" instead of "is".
Dan Story