Friday, 15 April 2011

c# - finding solution to make variables equal in the below case -



c# - finding solution to make variables equal in the below case -

var s1=new student{ id=1,name="sachin" } var s2=new student{ id=1,name="sachin" }

the question if s1 equal s2 reply false, method create s1 equal s2?

you have override equals , gethashcode, otherwise references compared:

public class pupil { public int id { get; set; } public string name { get;set; } public override bool equals(object obj) { pupil s2 = obj student; if (s2 == null) homecoming false; homecoming this.equals(s2); } public bool equals(student s) { if (s == null) homecoming false; homecoming id == s.id && name == s.name; } public override int gethashcode() { unchecked { int hash = 17; hash = hash * 23 + id; hash = hash * 23 + name.gethashcode(); homecoming hash; } } }

in illustration 2 students equal if both, id , name equal. alter accordingly.

it not necessary overload equals(student) , override gethashcode. recommended. read: guidelines overloading equals()

c#

No comments:

Post a Comment