I’m trying to find a struct I created earlier that has a specific value. Once I found it, I want to set variables on that struct. I don’t know how to do this. Is there a better way of doing this? Maybe classes? Or should structs work?
For example, my struct:
public struct MyTest
{
public string device;
public string status;
public string revision;
public string number;
public string ledmo;
}
My Test Code:
MyTest thisTest=new MyTest();
thisTest.device=blah;
thisTest.number=blah2;
MyTest thisTest2=new MyTest();
thisTest2.device=blah5;
thisTest2.number=blah6;
//Another Part in my code.
//Need to find the MyTest Structure that 'device' variable = the string 'blah'
var Foundit=MyTest.find(device==blah);
Foundit.revision=blah9999;
I’d use a class, because Mutable structs are evil
Basically, because every
structis copied, even if you do find the right struct, you’ll only ever change one copy. Lets sayMyTest.findfinds thisTest2 what happens is thisTo do this with a class you’ll need to keep every instance of the class you create in a list or other data structure, so you know you can look it up.
If you do this you also need to tell the list when you’re finished with each object, otherwise they’ll hang around forever and never get garbage collected.
Before I go any further, are you sure this is the best way to solve this problem?
Anyway, say your class is
MyData, you can put a static factory method on this calledCreate, which will put each new MyData object into a list.Everywhere you use a MyData you’ll need to
Deleteit when you’re finished with it.Your code becomes
Changing FoundIt now also changes
thisTestP.S.: It’s important that nothing outside
MyDatacannewan instance ofMyData. If it could, then there would be an instance ofMyDatathat you couldn’t find in AllInstances. Declaring the constructor private means a compiler error will be generated if code outside MyData tries something likevar someData = new MyData