开发者

How does interfaces get Equals and other methods defined in Object class

开发者 https://www.devze.com 2022-12-12 10:15 出处:网络
Code sample: List<ITest> tests = new List<ITest>(); tests.Add(new Test()); t开发者_Python百科ests.Add(new Test());

Code sample:

List<ITest> tests = new List<ITest>();
tests.Add(new Test());
t开发者_Python百科ests.Add(new Test());

Console.WriteLine(tests[0].Equals(tests[1]));

I came to know that in Java the public instance methods in Object classes get inserted into interface definition at compile time; Is this the behavior in C# also?


The same happens in C#: Equals and GetHashCode are methods implemented in the System.Object class. Your own classes can – but don’t always need to – override them.

Like in Java, the default object implementation performs reference equality (for classes). I.e. the following holds for two objects a and b: a.Equals(b) implies object.ReferenceEquals(a, b) (but not vice-versa, since a can be null). GetHashCode is implemented to match this behaviour.

For structs the situation is slightly different: Equals by default tries to compare all fields in the struct for pairwise equality.


Krishna, while your List is a list of ITest, you are adding Test objects, which inherit from System.Object. Try to override Equals in your Test object and put a logging statement if you doubt that.

0

精彩评论

暂无评论...
验证码 换一张
取 消