Is a Dictionary property newed up with the new keyword guaranteed to be ready before Awake?

Hi,

If I new up a property of type Dictionary in a MonoBehaviour with the new keyword, is it guaranteed to be ready before Awake?

It seems to be, but looking for 100% confirmation that it won’t suddenly throw a null ref.

using System.Collections.Generic;
using UnityEngine;

public class InventoryManagerMono : MonoBehaviour
{
    //Question: is this guaranteed to be ready before Awake every time? Seems to be, but looking for 100% confirmation.
    public Dictionary<InventoryType, Inventory> Inventories { get; set; } = new(); 

    private void Awake()
    {
        bool isNull = (Inventories == null) ? true : false;
        Debug.Log($"is it null? {isNull}");
    }
}

Thanks

Yes it’s fine. It will be inline initialised when Unity instantiates the C# object. And it’s quite literally impossible for Awake to be called before this point.

3 Likes

Perfect, thank you again!

Right. Field initializers are even called before the constructor (if the class has any). The only potential issue would be if a serialization package uses something like RuntimeHelpers.GetUninitializedObject. Though Unity doesn’t do this as creating an uninitialized object is dangerous in general as none of the fields are initialized, not even with zero. MonoBehaviours are created by the engine itself, so there is no room for this to happen (unless you manually create an instance, but in that case Awake would not be called at all as it would not be a valid MonoBehaviour anyways.)

3 Likes