class Cat { // Auto-implemented properties. public int Age { get; set; } public string Name { get; set; } } Cat cat = new Cat { Age = 10, Name = "Fluffy" };
The object initializers syntax allows you to create an instance, and after that it assigns the newly created object, with its assigned properties, to the variable in the assignment.
vs https://stackoverflow.com/a/19138412/432976
var albumData = new Album { Name = "Albumius", Artist = "Artistus", Year = 2013 };
is syntactic shorthand for this equivalent code:
var albumData = new Album(); albumData.Name = "Albumius"; albumData.Artist = "Artistus"; albumData.Year = 2013;
The two are identical after compilation.
Question: is this stype of construction + assignment thread safe? (ie, could another thread reading cat see the Cat between when it was created, and when Age and Name are assigned)?
The first seems to say it is, as it is after the properties are assigned, the variable gets assigned (the threadsafe order), the second says that at a compiled code level, the order is different.
if the second is true, is the following code sufficient to avoid the race condition of another thread seeing a half constructed cat?
var myNewCat = new Cat { Age = 10, Name = "Fluffy" };
sharedCat = myNewCat;
I realise that there are secondary race conditions here concerning if other threads see the oldCat or the newCat, but in this situation my only concern is that other threads must see a complete Cat, not a half constructed one.