using System.Collections.Generic;
using System.Runtime.CompilerServices;
public static void Main()
var propertyValues = new Dictionary<string, object>
var foo = ReflectionHelper.CreateInstance<Foo>(propertyValues);
Console.WriteLine($"Successfully created instance with Bar = {foo.Bar}");
catch (ArgumentException ex)
Console.WriteLine($"Failed to create instance: {ex.Message}");
public required string Bar { get; set; }
public static class ReflectionHelper
public static T CreateInstance<T>(Dictionary<string, object> propertyValues)
var constructorArgs = new object[] { };
T instance = (T)RuntimeHelpers.GetUninitializedObject(type);
var requiredProperties = type.GetProperties()
.Where(p => p.GetCustomAttribute<RequiredMemberAttribute>() != null);
foreach (var property in requiredProperties)
if (!propertyValues.ContainsKey(property.Name))
throw new ArgumentException($"Required property {property.Name} was not provided");
foreach (var kvp in propertyValues)
PropertyInfo? property = type.GetProperty(kvp.Key);
throw new ArgumentException($"Property {kvp.Key} does not exist on type {type.Name}");
throw new ArgumentException($"Property {kvp.Key} is read-only");
property.SetValue(instance, kvp.Value);
catch (ArgumentException ex)
throw new ArgumentException($"Invalid value type for property {kvp.Key}. Expected {property.PropertyType.Name}", ex);