Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lucas-zimerman/7904a15b54c8a1893ae83ce1b986f61c to your computer and use it in GitHub Desktop.
Save lucas-zimerman/7904a15b54c8a1893ae83ce1b986f61c to your computer and use it in GitHub Desktop.
C# Populate any object data with any information and also create it's subclasses. Good for testing Moq conversions.
private int _intValue;
private decimal _decimalValue;
private void SetValue(object target, PropertyInfo prop)
{
if (prop.CanWrite)
{
if (prop.PropertyType == typeof(int) || prop.PropertyType == typeof(int?))
{
prop.SetValue(target, _intValue++, null);
}
else if (prop.PropertyType == typeof(string))
{
prop.SetValue(target, DateTime.Now.ToString(), null);
}
else if (prop.PropertyType == typeof(bool) || prop.PropertyType == typeof(bool?))
{
prop.SetValue(target, true, null);
}
else if (prop.PropertyType == typeof(decimal) || prop.PropertyType == typeof(decimal?))
{
prop.SetValue(target, _decimalValue++, null);
}
}
}
private object CreateSubClass(Type type)
{
var instance = Activator.CreateInstance(type);
var typeProps = type.GetProperties();
foreach (var prop in typeProps)
{
SetValue(instance, prop);
}
return instance;
}
public void ObjectFillData(object @object)
{
var objectProps = @object.GetType().GetProperties();
foreach (var prop in objectProps)
{
if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
{
prop.SetValue(@object, CreateSubClass(prop.PropertyType));
}
else
{
SetValue(@object, prop);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment