private static void AddAttributes(ResultBox box, ValueHandler valueHandler, OptionAttribute optionAttribute) { object defaultValue = null; if (optionAttribute != null) { if (optionAttribute.Alias != null) box.StoreByName = optionAttribute.Alias; //validate that types for default value match Type dvt = optionAttribute.DefaultValue?.GetType(); if (optionAttribute.DefaultValue != null) { if (dvt != box.ResultType && dvt != typeof(string)) { throw new InvalidCastException($"Default value for option {box.Name} is of type {dvt.FullName} whereas the property has type {box.Name}. To fix this, either set default value to type {box.ResultType.FullName} or a string parseable to the target type."); } if (box.ResultType != typeof(string) && dvt == typeof(string)) { valueHandler.TryParse(box.ResultType, (string)optionAttribute.DefaultValue, out defaultValue); } } if (defaultValue == null) { defaultValue = optionAttribute.DefaultValue; } } if (defaultValue == null) defaultValue = GetDefaultValue(box.ResultType); box.DefaultResult = defaultValue; }
private static object GetDefaultValue(object defaultValue, ResultBox box, ValueHandler valueHandler) { object result = null; if (defaultValue != null) { //validate that types for default value match Type dvt = defaultValue?.GetType(); if (dvt != box.ResultType && dvt != typeof(string)) { throw new InvalidCastException($"Default value for option {box.Name} is of type {dvt.FullName} whereas the property has type {box.Name}. To fix this, either set default value to type {box.ResultType.FullName} or a string parseable to the target type."); } if (box.ResultType != typeof(string) && dvt == typeof(string)) { valueHandler.TryParse(box.ResultType, (string)defaultValue, out result); } } if (result == null) { result = defaultValue; } return(result); }