This is really stumping me today. I\'m sure its not that hard, but I have a System.Reflection.PropertyInfo object. I want to set its value based on the result of a database
This is a more polished version that maintains the .NET Runtime's functionality without adding any unnecessary custom code.
NOTE: This code written for .NET 3.5 SP1
namespace System {
public static class TypedDefaultExtensions {
public static object ToDefault(this Type targetType) {
if (targetType == null)
throw new NullReferenceException();
var mi = typeof(TypedDefaultExtensions)
.GetMethod("_ToDefaultHelper", Reflection.BindingFlags.Static | Reflection.BindingFlags.NonPublic);
var generic = mi.MakeGenericMethod(targetType);
var returnValue = generic.Invoke(null, new object[0]);
return returnValue;
}
static T _ToDefaultHelper() {
return default(T);
}
}
}
USAGE:
PropertyInfo pi; // set to some property info
object defaultValue = pi.PropertyType.ToDefault();
public struct MyTypeValue { public int SomeIntProperty { get; set; }
var reflectedType = typeof(MyTypeValue);
object defaultValue2 = reflectedType.ToDefault();
Rashad Rivera (OmegusPrime.com)