The problem is very simple and basic. At runtime, I want to be able to get the default value of a specific type. One solution is to use reflection and create a new instance of the object. But in this case you would use reflection more than one. Let's analyze the problem. There two group of types that we could have: Value Type and Reference Type. For Reference type the solution is very simple, because we need all the time to return NULL. For Value Type we can use Activator class to create a new instance of our type. public static class TypeExtension { public static object GetDefaultValue(this Type type) { if (type.IsValueType) { return Activator.CreateInstance(type); } return null; } } Assert.AreEqual(0,typeof(int).GetDefaultValue()); Assert.AreEqual(default(decimal), typeof(decimal).GetDefaultValue()); Assert.AreEqual(null, typeof(string).GetDefaultValue()); For this purpose I created an extension methods that returns ...
DREAMER, CRAFTER, TECHNOLOGY ENTHUSIAST, SPEAKER, TRAINER, AZURE MVP, SOLVING HARD BUSINESS PROBLEMS WITH CUTTING-EDGE TECHNOLOGY