-1

I am testing reflexibe object to make a method to obtain the changes betwen two object whitout know the class and i got this:

enter image description here

name, apellido and otromas are strings. edad its a int.

Efeyabel
  • 508
  • 4
  • 18
  • Its because you are using an object, the object may very well not be the same. Try converting it to ant int to compare or string if you want. `Convert.ToInt32(value) != Convert.ToInt32(value2)` if its just numbers in there this should work – EpicKip Feb 08 '17 at 09:45
  • 4
    Or use `value.Equals(value2)`. The `==` operator for object checks for reference equality first. By using `Equals` you call the concrete type's overload – Panagiotis Kanavos Feb 08 '17 at 09:46
  • you must cast them into value type if you want to compare their values – GSP Feb 08 '17 at 09:46
  • The value.Equeals(value2) works for me. I cant use Conver.ToInt32 because i need dont know the type of the object – Efeyabel Feb 08 '17 at 09:50
  • 2
    Please ask questions with posted as text code. You can add pictures if you want to demonstrate output. This way someone may easier be able to try your code and it's better for search (e.g. google index). – Sinatr Feb 08 '17 at 10:01
  • What is *reflexibe object* ? The equality test and reference test are different things and you may need to use different depending on scenario. Also look into [generics](http://stackoverflow.com/q/488250/1997232) and read about [boxing](https://msdn.microsoft.com/en-us/library/yz2be5wk.aspx) and why it is [bad](http://stackoverflow.com/q/13055/1997232). – Sinatr Feb 08 '17 at 10:06

1 Answers1

2

It's best to use object.Equals(value1, value2) in this cenario. The == sign actually executes object.ReferenceEquals and checks if the memory addresses of both objects are the same instead of the actual values.

var value1 = (object)1;
var value2 = (object)1;

Console.WriteLine(value1 == value2);                        // False
Console.WriteLine(object.ReferenceEquals(value1, value2));  // False
Console.WriteLine(value1.Equals(value2));                   // True
Console.WriteLine(object.Equals(value1, value2));           // True

And its better to use object.Equals instead of value1.Equals, because the following example changing value1 to null will cause an exception to be thrown

var value1 = (object)null;
var value2 = (object)1;

Console.WriteLine(value1 == value2);                       // False
Console.WriteLine(object.ReferenceEquals(value1, value2)); // False
Console.WriteLine(value1.Equals(value2));                  // NullReferenceException
Console.WriteLine(object.Equals(value1, value2));          // False
Ronald
  • 1,278
  • 2
  • 10
  • 14