c# - Increasing a field In an array of structures -


i have found in many places c# structures should treated immutable, me understand behavior of following code:

public partial class form1 : form {     private struct socsearchdomains     {         public string urlname;         public datetime lastrequeststampdate;         public int errorscount;          public socsearchdomains(string urlname, datetime requeststampdate)         {             urlname = urlname;             lastrequeststampdate = requeststampdate;             errorscount = 1;         }     }      private static socsearchdomains[] searchdomain { get; set; }     private static socsearchdomains searchdomain1 { get; set; }       public form1()     {         initializecomponent();         searchdomain = new socsearchdomains[1];         searchdomain[0] = new socsearchdomains("192.168.1.81", datetime.now);         searchdomain1 = new socsearchdomains("192.168.1.81", datetime.now);     }      private void button1_click(object sender, eventargs e)     {         messagebox.show(string.format("searchdomain[0]: {0}, searchdomain1: {1}", searchdomain[0].errorscount, searchdomain1.errorscount));         system.threading.interlocked.increment(ref searchdomain[0].errorscount);         system.threading.interlocked.increment(ref searchdomain1.errorscount);     } } 

basically, when try increment searchdomain1.errorscount, "cannot modify return value... because not variable", increment works searchdomain[0].errorscount (when commenting interlocked searchdomain1.errorscount). why behavior , safe use such interlocking (in array of structures) in multi-thread app?

responding why behavior, choosing between class , struct me respond: "value type arrays allocated inline, meaning array elements actual instances of value type". now, second question if safe or not, think it's better follow rule of when using structure (in same link): if immutable. so, better use class purpose.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -