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
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.ChangeTypereturnsobject. Therefore when the property type is actuallyInt32it will return a boxed integer.Your final line is comparing the references of two boxed values. Effectively you’re doing:
You can use
Equalsinstead – and the staticobject.Equalsmethod handily copes with null references, should that be an issue: