Which is best for data store Struct/Classes?

后端 未结 9 1894
无人共我
无人共我 2020-11-30 05:29

We have seen lots of discussion in SO regarding the class vs struct in c#. Mostly ended with conclusions saying its a heap/stack memory allocation. And reco

9条回答
  •  被撕碎了的回忆
    2020-11-30 06:19

    A pretty cool, not so well known advantage of Structs over Classes is that there is an automatic implementation of GetHashcode and Equals in structs.
    That's pretty useful when keys are required for dictionaries

    The struct implementation of GetHashcode and Equals is based on the binary content of the struct instances + reflection for the reference members (like String members and other instances of classes)

    So the following code works for GethashCode/Equals :

    public struct Person
    {
        public DateTime Birthday { get; set; }
        public int Age{ get; set; }
        public String Firstname { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person { Age = 44, Birthday = new DateTime(1971, 5, 24), Firstname = "Emmanuel" };
            Person p2 = new Person { Age = 44, Birthday = new DateTime(1971, 5, 24), Firstname = "Emmanuel" };
            Debug.Assert(p1.Equals(p2));
            Debug.Assert(p1.GetHashCode() == p2.GetHashCode());
        }
    }
    

    Both assertions succeed when Person is a struct Both assertions fail if Person is a class instead of a struct

    Reference : https://msdn.microsoft.com/en-Us/library/2dts52z7%28v=vs.110%29.aspx

    Regards, best coding

提交回复
热议问题