Ok.. I have a really awkward problem that I believe is related with how C# handles value types vs reference types but I’m just not sure what exactly the bug is.
public partial class LogicSimulationViewerForm : Form
{
private Dictionary<string, PointStruct> pointValues;
private void SearchPoint(string code)
{
ReadDefaultPointValuesResponse result = ddcdao.ReadDefaultPoint(points);
pointValues = new Dictionary<string, PointStruct>();
for (int j = 0; j < result.pointidentifier.Length; j++)
{
if (!pointValues.ContainsKey(result.pointidentifier[j]))
{
PointStruct ps = new PointStruct();
ps.name = "Random String";
ps.pointidentifier = result.pointidentifier[j];
ps.outofservice = result.outofservice[j];
pointValues.Add(result.pointidentifier[j], ps);
...
pointValues is stored as a private field in a class. Now in the same class but in a different function, if I try to do the following:
PointStruct ps = pointValues[s];
MessageBox.Show(ps.name);
MessageBox.Show(ps.pointidentifier);
MessageBox.Show(ps.outofservice);
The ps.pointidentifier and ps.outofservice is displayed correctly but ps.name is always returned as null no matter what I do. How can I fix this issue?
Edit: Upon request, I am adding more code to further illustrate the problem:
public struct PointStruct
{
public string pointidentifier;
public string affect;
public string outofservice;
public string priorityarray;
public string pointtype;
public string alarmstate;
public string correctvalue;
public string presentvalue;
public string name;
public string test;
}
As long as there is no voodoo (explicit field layouts, property indirection, etc), there is absolutely no reason why a field should wipe itself, regardless of whether it is a
classor astruct.If it was a
class, we could perhaps put that down to a careless update somewhere else, i.e.which would of course update the same fundamental object as the one referenced by the dictionary. But that doesn’t apply to a
struct, since the copies are separate (unless updating directly in an array).The only way I can see of causing that, given that you state that
pointValues.Add(...)is only used in one place, is that you are overwriting it elsewhere via the indexer:All that said, though; unless you have some very specific reasons, there is very little purpose for
PointStructto be astruct. That looks to me like it should be aclass. It is very “fat” for astruct. Also; in most cases,structs should be immutable.