Skip to content

Commit

Permalink
Make DefaultValueAttribute fall back to TypeConverter
Browse files Browse the repository at this point in the history
  • Loading branch information
ericstj committed Aug 7, 2018
1 parent ab9b451 commit 17ac7be
Showing 1 changed file with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public class DefaultValueAttribute : Attribute
/// This is the default value.
/// </devdoc>
private object _value;
private static Func<Type, string, object> s_convertMethod = GetConvertMethod();

/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class, converting the
Expand All @@ -44,16 +45,44 @@ public DefaultValueAttribute(Type type, string value)
{
_value = TimeSpan.Parse(value);
}
else
else if (type.Module == typeof(string).Module)
{
_value = Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
else
{
_value = s_convertMethod(type, value);
}
}
catch
{
}
}

private static Func<Type, string, object> GetConvertMethod()
{
var typeDescriptorType = Type.GetType(
"System.ComponentModel.TypeDescriptor, System, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
throwOnError: false);
var typeConverterType = Type.GetType(
"System.ComponentModel.TypeConverter, System, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
throwOnError: false);

if (typeDescriptorType != null && typeConverterType != null)
{
var typeDescriptorTypeGetConverter = typeDescriptorType.GetMethod("GetConverter", new Type[] { typeof(Type) });
var typeConverterConvertFromInvariantString = typeConverterType.GetMethod("ConvertFromInvariantString", new Type[] { typeof(string) });
return new Func<Type, string, object>((t, s) =>
typeConverterConvertFromInvariantString.Invoke(
typeDescriptorTypeGetConverter.Invoke(null, new[] { t }),
new[] { s }));
}
else
{
return new Func<Type, string, object>((t, s) => null);
}
}

/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a Unicode
/// character.</para>
Expand Down

0 comments on commit 17ac7be

Please sign in to comment.