private static object GenerateDictionary(Type dictionaryType, int size,
Dictionary<Type, object> createdObjectReferences) {
var typeK = typeof (object);
var typeV = typeof (object);
if (dictionaryType.IsGenericType)
{
var genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
var result = Activator.CreateInstance(dictionaryType);
var addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
var containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
var objectGenerator = new ObjectGenerator();
for (var i = 0; i < size; i++)
{
var newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
var containsKey = (bool) containsMethod.Invoke(result, new[] {newKey});
if (!containsKey)
{
var newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new[] {newKey, newValue});
}
}
return result;
}