C# struct with object as data member
- by source-energy
As we know, in C# structs are passed by value, not by reference. So if I have a struct with the following data members:
private struct MessageBox
{
// data members
private DateTime dm_DateTimeStamp; // a struct type
private TimeSpan dm_TimeSpanInterval; // also a struct
private ulong dm_MessageID; // System.Int64 type, struct
private String dm_strMessage; // an object (hence a reference is stored here)
// more methods, properties, etc ...
}
So when a MessageBox is passed as a parameter, a COPY is made on the stack, right?
What does that mean in terms of how the data members are copied?
The first two are struct types, so copies should be made of DateTime and TimeSpan. The third type is a primitive, so it's also copied. But what about the dm_strMessage, which is a reference to an object? When it's copied, another reference to the same String is created, right? The object itself resides in the heap, and is NOT copied (there is only one instance of it on the heap.) So now we have to references to the same object of type String. If the two references are accessed from different threads, it's conceivable that the String object could be corrupted by being modified from two different directions simultaneously. The MSDN documentation says that System.String is thread safe. Does that mean that the String class has a built-in mechanism to prevent an object being corrupted in exactly the type of situation described here?
I'm trying to figure out if my MessageBox struct has any potential flaws / pitfalls being a structure vs. a class.
Thanks for any input.
Source.Energy.