I have found in many places that C# structures should be treated as immutable, but I would like somebody help me to understand the behavior of the 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 I try to increment SearchDomain1.ErrorsCount
, I get a "cannot modify the return value... because it is not a variable", but increment works for searchDomain[0].ErrorsCount
(when commenting Interlocked for SearchDomain1.ErrorsCount
).
Why is that behavior and is it safe to use such Interlocking (in an array of structures) in a multi-thread app?