-1

I am trying to compare 2 objects with properties and child properties. The below code always return false even if object values are matching. What is the best option to compare in this case?

Student a = new Student();
a.Name = "john";
a.Address ="CA";                        
//a.StudDetails.Location = "LA";
//a.StudDetails.Study = "MBA";
//a.StudDetails.Friends = new string[] { "X", "Y"};

Student b = new Student();
b.Name = "john";
b.Address = "CA";
//b.StudDetails.Location = "LA";
//b.StudDetails.Study = "MBA";
//b.StudDetails.Friends = new string[] { "X", "Y"};
bool x = Equals(a, b);
if (x)
{
    Console.WriteLine("matched");
}
else
{
    Console.WriteLine("Not Matched");
}


public class Student
{
    public string Name;
    public Details StudDetails;
    public string Address;
}

public class Details
{
    public string Study;
    public string Location;
    public string[] Friends;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kurkula
  • 6,386
  • 27
  • 127
  • 202
  • 1
    Default `Equals` method compares only references, returns `true` only if both variables poionting to the same object – Fabio Oct 02 '16 at 06:12
  • And to avoid future problems - notice that you need to do that also for `Details` and also you must initialize the `StudDetails` property first otherwise you will get a `NullReferenceException` – Gilad Green Oct 02 '16 at 06:47
  • Equals determines whether the specified object is equal to the current object. since variable `b` is another instance of `Student`. and not from the variable 'a' it returns false. it is comparing two "Reference" type (stores from heap). but if you instance `b` from `a` it will return true, just simply saying `Student c = b;` if you want to learn more about "Reference" vs "Value" type see this link: https://msdn.microsoft.com/en-us/library/t63sy5hs.aspx – Jeric Cruz Oct 02 '16 at 06:48

1 Answers1

1

You have to implement Equals on Student https://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx

public class Details
{
    public string Study;
    public string Location;
    public string[] Friends;
}

public class Student
{
  public string Name;
  public Details StudDetails;
  public string Address;  

  public override bool Equals(Object obj) 
  {
  // Check for null values and compare run-time types.
  if (obj == null || GetType() != obj.GetType()) 
   return false;

  Student s = (Student)obj;
  return (Name == s.Name) && (Address == s.Address);
  }
}

Student a = new Student();
a.Name = "john";
a.Address ="CA";                        
//a.StudDetails.Location = "LA";
//a.StudDetails.Study = "MBA";
//a.StudDetails.Friends = new string[] { "X", "Y"};

Student b = new Student();
b.Name = "john";
b.Address = "CA";
//b.StudDetails.Location = "LA";
//b.StudDetails.Study = "MBA";
//b.StudDetails.Friends = new string[] { "X", "Y"};

bool x = a.Equals(b);
Console.WriteLine( x );

This code prints "True".

espino316
  • 452
  • 4
  • 8