private static void SaveObject(SaveStateContext context, object obj, string keyPath) { var type = obj.GetType(); foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { var saveChildrenAttribute = field.GetCustomAttribute <SaveChildrenAttribute>(); var saveAttribute = field.GetCustomAttribute <SaveAttribute>(); // If both the SaveChildrenAttribute and SaveAttribute exist on a field, ignore the SaveAttribute. if (saveChildrenAttribute is not null) { var value = field.GetValue(obj); if (value is not null) { var name = saveChildrenAttribute.Name ?? field.Name; SaveObject(context, value, $"{keyPath}.{name}"); } } else if (saveAttribute is not null) { var name = saveAttribute.Name ?? field.Name; context.AddToState($"{keyPath}.{name}", field.GetValue(obj)); } } foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { var saveChildrenAttribute = property.GetCustomAttribute <SaveChildrenAttribute>(); var saveAttribute = property.GetCustomAttribute <SaveAttribute>(); // If both the SaveChildrenAttribute and SaveAttribute exist on a property, ignore the SaveAttribute. if (saveChildrenAttribute is not null) { var value = property.GetValue(obj); if (value is not null) { var name = saveChildrenAttribute.Name ?? property.Name; SaveObject(context, value, $"{keyPath}.{name}"); } } else if (saveAttribute is not null) { var name = saveAttribute.Name ?? property.Name; context.AddToState($"{keyPath}.{name}", property.GetValue(obj)); } } }