2

I have a method that gets two parameters: the first is a Type to convert to and the second is the object to be converted. I tried to convert the object like this:

public static void method1(Type convertTo, object toBeConverted)
{
    toBeConverted = (convertTo)toBeConverted;
}

But when I do that I get an error: "convertTo is a variable but is used like a type". How can I make this casting work(without checking the type of convertTo and converting according to this type)?

HilaB
  • 179
  • 2
  • 14

2 Answers2

6

Looks like you want the ChangeType method. e.g.

toBeConverted = Convert.ChangeType(toBeConverted, convertTo)

Note that ChangeType requires that toBeConverted implements the IConvertible interface.

Alternatively, you could use a TypeConverter:

var converter = TypeDescriptor.GetConverter(convertTo);
toBeConverted = converter.ConvertFrom(toBeConverted);

This requires that toBeConverted has a default TypeConverter, but this should work with nullable types. Note that TypeConverters have a CanConvertFrom method that will allow you to determine at runtime whether or not the conversion is supported.

These are not the only ways to do this, but the above should work in most cases. If you are working with custom types, then you would have to either implement your own TypeConverter or implement IConvertible as appropriate. If performance is a consideration, then they are not the fastest, but unless this is an issue, I wouldn't worry about it.

bornfromanegg
  • 2,826
  • 5
  • 24
  • 40
4

You can do this 2 ways - one with generics and one with Convert class

public static void method1(Type convertTo, object toBeConverted)
{
    var convertedValue = Convert.ChangeType(toBeConverted,convertTo);
}

public static void method2<TConvert>(object toBeConverted)
{
    var convertedValue = (TConvert)toBeConverted;
}

Both methods will throw an exception if the type cannot be converted.

Jamiec
  • 133,658
  • 13
  • 134
  • 193