Interview Question

Senior Applications Developer Interview

-Toronto, ON

RBC

What would the count for the list of it. public class Test { string Data; int Id; public Test(int id, string data) { Data = data; Id = id; } } static void Main(string[] args) { List<Test> list = new List<Test>(); list.Add(new Test(10, "test")); var d = new Test(10, "test"); if (!list.Contains(d)) list.Add(d); Console.WriteLine("Count of the list is : " + list.Count); Console.ReadLine(); } } What to do to make count 1?

AnswerAdd Tags

Interview Answers

2 Answers

0

First count would be 2. To make it 1. Add override method as following. public override bool Equals(object obj) { if (obj == null) return false; var d = (Test)obj; return (d.Data == Data && d.Id == Id); }

Anonymous on

0

public class Test : IEquatable { string Data; int Id; public Test(int id, string data) { Data = data; Id = id; } public bool Equals(Test other) { return this.Id == other.Id && this.Data == other.Data; } }

Implement IEquatable on

Add Answers or Comments

To comment on this, Sign In or Sign Up.