Sorry for this newbie question, I’m very new to C# and it’s semantics. I have the following struct:
public struct MT5Command{
public MT5CommandType Type{ get; set;}
public AutoResetEvent ThreadWaitHandle { get; set; }
public object InParam { get; set; }
public object OutParam { get; set; }
}
And this code snippet:
MT5Command Cmd = new MT5Command();
Cmd.Type = MT5CommandType.GetServerInformation;
Cmd.ThreadWaitHandle = waitHandle.Value;
attributes = new ServerAttributes();
Cmd.OutParam = attributes;
....
ServerAttributes SrvAttributes = new ServerAttributes();
Cmd.OutParam = (ServerAttributes)SrvAttributes;
The last line does not compile: Cannot modify members of ‘command’ because it is a ‘foreach iteration variable’
How is it possible to assign the OutParam field to another ServerAttributes struct?
This is the outer for-each loop:
foreach (MT5Command Cmd in mCommandQueue.GetConsumingEnumerable())
{
...
}
Thanks, Juergen
You can’t, in this case. You haven’t given the full snippet, but I suspect it’s something like this:
Now because
MT5Commandis a struct, you’re getting a copy of whatever value is insomeCollection. Changing the property almost certainly wouldn’t do what you wanted it to anyway. The compiler is protecting you from yourself, by making thecommandvariable read-only. You could do this:… but I strongly suspect that’s not what you want.
As a rule, it’s a really bad idea to have mutable structs like the one you’ve come up with – and it doesn’t sound like that should be a struct in the first place.
For more information: