Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created March 28, 2022 07:45
Show Gist options
  • Save jmcd/e87ae4d96f3bd7cf03d3f2b5f75bb7be to your computer and use it in GitHub Desktop.
Save jmcd/e87ae4d96f3bd7cf03d3f2b5f75bb7be to your computer and use it in GitHub Desktop.
Hack to magic up objects with random property values
using System.Text;
public static class AutoGarbage
{
private const string Chars = "qwertyuiopasdfghjklzxcvbnm1234567890";
public static T Next<T>(this Random random) => (T)Next(random, typeof(T));
private static object Next(this Random random, Type type)
{
var o = type.GetConstructor(Type.EmptyTypes)!.Invoke(null);
foreach (var propInfo in type.GetProperties())
{
var propVal = MakeProperty(random, propInfo.PropertyType);
propInfo.GetSetMethod()!.Invoke(o, new[] { propVal });
}
return o;
}
private static object MakeProperty(this Random random, Type propertyType)
{
object propVal;
Type? listItemType;
if (propertyType == typeof(int))
{
propVal = random.Next();
}
else if (propertyType == typeof(string))
{
var len = random.Next(20);
var s = new StringBuilder();
for (var i = 0; i < len; i++)
{
s.Append(Chars[random.Next(0, Chars.Length)]);
}
propVal = s.ToString();
}
else if (propertyType == typeof(bool))
{
propVal = random.Next() % 2 == 0;
}
else if ((listItemType = propertyType.ListItemType()) is not null)
{
propVal = propertyType.GetConstructor(Type.EmptyTypes)!.Invoke(null);
var addMethod = propertyType.GetMethod(nameof(List<object>.Add), new[] { listItemType })!;
for (var i = 0; i < random.Next(10); i++)
{
var item = Next(random, listItemType);
addMethod.Invoke(propVal, new[] { item });
}
}
else
{
propVal = Next(random, propertyType);
}
return propVal;
}
private static Type? ListItemType(this Type t)
{
if (!t.IsGenericType) { return default; }
return t.GetGenericTypeDefinition() != typeof(List<>) ? default : t.GenericTypeArguments[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment