Juergen
Juergen

Reputation: 3743

C# Assign/cast to object fields in a struct

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

Upvotes: 1

Views: 1234

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500365

You can't, in this case. You haven't given the full snippet, but I suspect it's something like this:

foreach (MT5Command command in someCollection)
{
    // Code as posted
}

Now because MT5Command is a struct, you're getting a copy of whatever value is in someCollection. Changing the property almost certainly wouldn't do what you wanted it to anyway. The compiler is protecting you from yourself, by making the command variable read-only. You could do this:

MT5Command copy = command;
copy.OutParam = SrvAttributes;

... 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:

Upvotes: 6

Related Questions