Initialization readability and multithreading

Consider following snippet of code:

            // My preference
            var myItem = new Item();
            myItem.some1 = 123;
            myItem.some2 = 456;
            myItem.some3 = 789;
            myItem.some4 = 111;
            myItem.some5 = new OtherItem(myItem);
         
            // IDE suggestion
            var myItem = new Item
            {
                some1 = 123,
                some2 = 456,
                some3 = 789,
                some4 = 111
            };
            myItem.some5 = new OtherItem(myItem);

I would like to do the former, but my IDE suggests doing the latter. When I click on explanation the website says:
Object and collection initializers offer more concise syntax. Besides, initializers are useful in multi-threading."

My preference looks cleaner to me but there will be elements of DOTS and BurstCompiler and it says “are useful in multi-threading”. Am I kneecapping myself in the future? Should I swap to the suggestion or stay with the former? This doesn’t bother me a lot, this code will be within a method and will barely be copied.

It is useful in multi-threading only when you have concurrent access to the same field from different threads and one thread could read filed before another has finished creation.

For example

private Item myItem;

public void Initialize()
{
    myItem = new Item();          
    myItem.some1 = 123;       
   // Calling GetSum() from other thread could happen here and it's result will be uncorrent
    myItem.some2 = 456;          
    myItem.some3 = 789;          
    myItem.some4 = 111;
}

public int GetSum()
{
    if (myItem == null)
        return 0;
  
    return myItem.some1 + myItem.some2 + myItem.some3 + myItem.some4;
}

with Object initializers, myItem will be assigned only after all fields are assigned so another thread cant read half initialized object.

But in my opinion, you do not need to think about the object initializers feature in the context of multi-threading. The benefit is so small that could be neglected.
This feature is all about style IMO:)

UPD. Just read JetBrains explanation and they describe the same half assign example in the first code snippet

1 Like

People always think the benefit is small until they have to debug a race condition by hand. :smile:

@JackS1001 you do what you want, obviously, but take this from a seasoned developer: your annoyance getting used to a form of initialization is much smaller than your annoyance will be if this causes a race condition in your multi-threaded application and you need to find the bug.