AssertPropertiesAreNonNull

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

public class SomethingNested
{
	[Required]
	public string SomeString { get; set; }

	[Required]
	public int SomeNumber { get; set; }

	public bool SomeBoolean { get; set; }

	public List<string> SomeStringList { get; set; }

}

public class MyWidget
{
	[Required]
	public SomethingNested SomethingNested { get; set; }

	public string SomeString { get; set; }

	public int SomeNumber { get; set; }

	public bool SomeBoolean { get; set; }

	[Required]
	public List<string> SomeStringList { get; set; }
}

public class Program
{
	public static void Main()
	{
		var myWidget = new MyWidget
		{
			SomethingNested = new SomethingNested
			{
				SomeString = null,
				SomeNumber = 123,
				SomeBoolean = true,
				SomeStringList = new List<string> { "a", "b", null }
			},
			SomeString = null,
			SomeNumber = 123,
			SomeBoolean = true,
			SomeStringList = null
		};

		// Only run for required properties of myWidget
		// AssertPropertiesAreNonNull(myWidget);
		
		// Run for ALL properties in myWidget
		AssertPropertiesAreNonNull(myWidget, false);
	}
	
	// Asserts that all required properties (via the 'Required' attribute) be non null
	// Optionally include all properties if desired
	private static void AssertPropertiesAreNonNull<T>(T obj, bool onlyRequiredProperties = true)
	{
		if (obj == null)
		{
			return;
		}

		var objType = obj.GetType();

		// Get either all or only required properties
		var properties = onlyRequiredProperties ? objType.GetProperties()
			.Where(x => x.GetCustomAttributes(false).OfType<RequiredAttribute>().Any()) : 
		objType.GetProperties();

		foreach (var property in properties)
		{
			var propValue = property.GetValue(obj, null);
			var elems = propValue as IList<object>;

			// Another layer 
			if (elems != null)
			{
				foreach (var item in elems)
				{
					AssertPropertiesAreNonNull(item, onlyRequiredProperties);
				}
			}
			else
			{
				if (property.PropertyType.Assembly == objType.Assembly)
				{
					AssertPropertiesAreNonNull(propValue, onlyRequiredProperties);
				}
				// Reached the end of the tree
				else
				{
					Console.WriteLine($"Evaluating {property.Name}...");
					
					// Prepare error message
					var errorMessage = $"Property '{property.Name}' is null!";
					
					// Various options for what you want to do if a property is null. 
					// Toggle with comments or delete to your liking:
					
					// Simply log it out:
					if (propValue == null) 
					{
						Console.WriteLine(errorMessage);
					}

					// If using Shouldly:
					//propValue.ShouldNotBeNull();

					// Or simply the angry way - throw an exception!
					//if (propValue == null)
                    //{
				    //  throw new Exception(errorMessage);
                    //}
				}
			}
		}
	}
}
;