lundi 17 février 2020

C# recursively check all values not null [duplicate]

Without wanting to reinvent the wheel, is there a dotnet nuget library to perform checks on a object recursively for argument checking?

If not, how would I convert the code to check if a property is null, and if a type that can hold properties of its own, recursively check that type?

public static class Assert
{
    public static void AllPropertiesNotNull<T>(T obj)
    {
        if (obj == null)
            throw new ArgumentNullException(nameof(obj));

        var emptyProperties = typeof(T)
                                .GetProperties()
                                .Select(prop => new { Prop = prop, Val = prop.GetValue(obj, null) })
                                .Where(val => IsEmpty((dynamic)val.Val))
                                .Select(val => val.Prop.Name)
                                .ToList();

        if (emptyProperties.Count > 0)
            throw new ArgumentNullException(emptyProperties.First());
    }

    private static bool IsEmpty(object o) { return o == null; }
}




Aucun commentaire:

Enregistrer un commentaire