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
Try the following methods, which I have written and tested against thousands of types:
///
/// [ public static T GetDefault< T >() ]
///
/// Retrieves the default value for a given Type
///
/// The Type for which to get the default value
/// The default value for Type T
///
/// If a reference Type or a System.Void Type is supplied, this method always returns null. If a value type
/// is supplied which is not publicly visible or which contains generic parameters, this method will fail with an
/// exception.
///
///
public static T GetDefault()
{
return (T) GetDefault(typeof(T));
}
///
/// [ public static object GetDefault(Type type) ]
///
/// Retrieves the default value for a given Type
///
/// The Type for which to get the default value
/// The default value for
///
/// If a null Type, a reference Type, or a System.Void Type is supplied, this method always returns null. If a value type
/// is supplied which is not publicly visible or which contains generic parameters, this method will fail with an
/// exception.
///
///
public static object GetDefault(Type type)
{
// If no Type was supplied, if the Type was a reference type, or if the Type was a System.Void, return null
if (type == null || !type.IsValueType || type == typeof(void))
return null;
// If the supplied Type has generic parameters, its default value cannot be determined
if (type.ContainsGenericParameters)
throw new ArgumentException(
"{" + MethodInfo.GetCurrentMethod() + "} Error:\n\nThe supplied value type <" + type +
"> contains generic parameters, so the default value cannot be retrieved");
// If the Type is a primitive type, or if it is another publicly-visible value type (i.e. struct), return a
// default instance of the value type
if (type.IsPrimitive || !type.IsNotPublic)
{
try
{
return Activator.CreateInstance(type);
}
catch (Exception e)
{
throw new ArgumentException(
"{" + MethodInfo.GetCurrentMethod() + "} Error:\n\nThe Activator.CreateInstance method could not " +
"create a default instance of the supplied value type <" + type +
"> (Inner Exception message: \"" + e.Message + "\")", e);
}
}
// Fail with exception
throw new ArgumentException("{" + MethodInfo.GetCurrentMethod() + "} Error:\n\nThe supplied value type <" + type +
"> is not a publicly-visible type, so the default value cannot be retrieved");
}
The first (generic) version of GetDefault is of course redundant for C#, since you may just use the default(T) keyword.
Enjoy!