Hi Guys, We have 2 objects A & B: A is system.string and B is some .net primitive type (string,int etc). we want to write generic code to assign the converted (parsed) value of B into A. Any suggestions? Thanks, Adi Barda
What's wrong with the already existing System.Convert class and the IConvertible interface?
As already mentioned, System.Convert and IConvertible would be the first bet. If for some reason you cannot use those (for instance, if the default system conversions for the built in types is not adequate for you), one approach is to create a dictionary that holds delegates to each conversion, and make a lookup in that to find the correct conversion when needed.
For instance; when you want to convert from String to type X you could have the following:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(SimpleConvert.To<double>("5.6"));
Console.WriteLine(SimpleConvert.To<decimal>("42"));
}
}
public static class SimpleConvert
{
public static T To<T>(string value)
{
Type target = typeof (T);
if (dicConversions.ContainsKey(target))
return (T) dicConversions[target](value);
throw new NotSupportedException("The specified type is not supported");
}
private static readonly Dictionary<Type, Func<string, object>> dicConversions = new Dictionary <Type, Func<string, object>> {
{ typeof (Decimal), v => Convert.ToDecimal(v) },
{ typeof (double), v => Convert.ToDouble( v) } };
}
Obviously, you would probably want to do something more interesting in your custom conversion routines, but it demonstrates the point.
The most pragmatic and versatile way to do string conversions is with TypeConverter
:
public static T Parse<T>(string value)
{
// or ConvertFromInvariantString if you are doing serialization
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}
More types have type-converters than implement IConvertible
etc, and you can also add converters to new types - both at compile-time;
[TypeConverter(typeof(MyCustomConverter))]
class Foo {...}
class MyCustomConverter : TypeConverter {
// override ConvertFrom/ConvertTo
}
and also at runtime if you need (for types you don't own):
TypeDescriptor.AddAttributes(typeof(Bar),
new TypeConverterAttribute(typeof(MyCustomConverter)));