Skip to content

Instantly share code, notes, and snippets.

@maslevx
Created June 21, 2015 04:21
Show Gist options
  • Save maslevx/635a3b5085928dd8dad9 to your computer and use it in GitHub Desktop.
Save maslevx/635a3b5085928dd8dad9 to your computer and use it in GitHub Desktop.
filehelpers field converter
public sealed class CustomFormatConverter<T> : ConverterBase where T : IFormattable
{
private string _formatString;
private IFormatProvider _formatProvider;
private Type _objType;
#region constructors
public CustomFormatConverter(string Format)
: this(Format, null)
{ }
public CustomFormatConverter(string Format, IFormatProvider Provider)
{
_formatString = Format;
_formatProvider = Provider;
_objType = typeof(T);
}
#endregion
public override string FieldToString(object from)
{
if (from == null)
return String.Empty;
return ((IFormattable)from).ToString(_formatString, _formatProvider);
}
public override object StringToField(string from)
{
object rtnVal;
TypeConverter converter = TypeDescriptor.GetConverter(_objType);
if (converter == null)
throw new ConvertException(from, _objType, "Unable to get converter for type " + _objType.ToString());
try
{
rtnVal = converter.ConvertFromString(from);
}
catch (Exception E)
{
throw new ConvertException(from, _objType, E.Message);
}
return rtnVal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment