views:

29

answers:

1

Can someone explain why this is occurring? The code below was executed in the immediate window in vs2008. The prop is an Int32 property (id column) on an object created by the entity framework.

The objects entity and defaultEntity were created using Activator.CreateInstance();

Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) == Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) false

+1  A: 

I assume you're wondering why the third line prints false. If you want to know why the first two lines are printing 0, you'll have to post more code and tell us what you actually expected.

Convert.ChangeType returns object. Therefore when the property type is actually Int32 it will return a boxed integer.

Your final line is comparing the references of two boxed values. Effectively you're doing:

object x = 0;
object y = 0;
Console.WriteLine (x == y); // Prints False

You can use Equals instead - and the static object.Equals method handily copes with null references, should that be an issue:

object x = 0;
object y = 0;
Console.WriteLine (object.Equals(x, y)); // Prints True
Jon Skeet
Yep, I ended up figuring that out with some help from a co-worker. .Equals gets me what I want.Is there a way to check if that object is a string or integer without explicitly checking each condition?
Brian
What do you mean by "checking each condition"? You can either use "is" or call GetType().
Jon Skeet