C# Reflection: Nested Objects Contains Value

posted in: Uncategorized | 0

So, let’s say I have a set of objects where object B has an instance of object A as one of it’s properties.

public class ObjectB
{
	public int Id { get; set; }
	public string Name { get; set; }
}

public class ObjectA
{
	public int Id { get; set; }
	public string Name { get; set; }
	public ObjectB Child { get; set; }
}

I want to find if SOMEWHERE ObjectA or ObjectB, a value is contained.. basically an indexOf on all properties of an object and all nested objects. Let’s write an extension method to do this.

public static class ReflectionHelper
{
	public static bool ContainsValue(this Object obj, string value)
	{
		foreach (var property in obj.GetType().GetProperties())
		{
			var val = property.GetValue(obj, null);

			if (property.PropertyType.FullName != "System.String"
				&& !property.PropertyType.IsPrimitive)
			{

				return val.ContainsValue(value);
			}

			if (val.ToString().ToLower().IndexOf(value) > -1)
			{
				return true;
			}
		}
		return false;
	}
}

Example usage:

obj.ContainsValue("test");
My name is Andrew McGivery. I currently work full time as an application developer at Manulife Financial in Canada. My current passion is building and leading highly engaged teams where employee happiness, learning, and growth is a priority.

Leave a Reply