Untitled
unknown
plain_text
18 days ago
2.3 kB
2
Indexable
using System; using System.Linq; using System.Reflection; public class ObjectPopulator { public static T CreateExampleInstance<T>() where T : class, new() { return (T)CreateExampleInstance(typeof(T)); } private static object CreateExampleInstance(Type type) { if (type == null || !type.IsClass) return null; // Handle string separately to avoid infinite loops if (type == typeof(string)) return "ExampleString"; // Try creating an instance using the default constructor object instance; try { instance = Activator.CreateInstance(type); } catch { return null; } // Populate properties foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanWrite)) { object value = GetExampleValue(property.PropertyType); property.SetValue(instance, value); } return instance; } private static object GetExampleValue(Type type) { if (type == typeof(string)) return "ExampleString"; if (type == typeof(int)) return 42; if (type == typeof(double)) return 3.14; if (type == typeof(bool)) return true; if (type == typeof(DateTime)) return DateTime.Now; if (type.IsEnum) return Enum.GetValues(type).GetValue(0); if (type.IsClass) return CreateExampleInstance(type); // Recursively instantiate return null; } } // Example usage public class Person { public string Name { get; set; } public int Age { get; set; } public Address HomeAddress { get; set; } } public class Address { public string Street { get; set; } public int ZipCode { get; set; } } class Program { static void Main() { Person examplePerson = ObjectPopulator.CreateExampleInstance<Person>(); Console.WriteLine($"Name: {examplePerson.Name}, Age: {examplePerson.Age}"); Console.WriteLine($"Address: {examplePerson.HomeAddress?.Street}, ZipCode: {examplePerson.HomeAddress?.ZipCode}"); } }
Editor is loading...
Leave a Comment