generically convert to target type

J

John A Grandy

How to generically convert an object to a target type ?

So .... I'm looking for something like :

DateTime value = new DateTime( 2008, 9, 18, 8, 35, 31, 10 );
System.Type targetType = typeof(TimeSpan);
object convertedValue = ConvertToType( value, targetType );

public static object ConvertToType( object value, System.Type targetType )
{
return Convert.ToType( value, targetType ); // Convert.ToType()
doesn't exist
}
 
M

Marc Gravell

Well, there is Convert.ChangeType which works in the way you ask - but
note that there is no sensible conversion defined from DateTime to
TimeSpan. If you /want/ a timespan from a DateTime, then you usually
mean "the offset from [this] origin", so just use subtraction
(DateTime - DateTime => TimeSpan).

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top