Question

For some reason I need to cast/convert a DateTime into one of many custom objects

This proves to be very difficult to do in a nice generic fashion.

I am thinking of implementing an extension method on object or perhaps extending DateTimeConverter.

But then what would be the generic way to handle this, I have an object and a destination type and at the moment I am using System.ConvertTo(..) but this is clearly limited because it only supports converting to .NET types and cant be extended.

Any ideas?

Was it helpful?

Solution

You could add a constructor for your TimeStamp that takes DateTime as a parameter.

public class TimeStamp
{
   public TimeStamp(DateTime dateTime, ...)
   {
    // Your code here to convert from dateTime to TimeStamp
   }
}

Then later ...

 DestType Convert<DestType>( Object linqResult )   
 {
  DestType result;
  if( linqResult is DateTime && DestType is TimeStamp )
  {
   DateTime dbTime = linqResult as DateTime;
   result = new TimeStamp( dbTime );
  }
  ...
  return result;
 }

You could probably even extend this with all kinds of reflection and constructors etc. But if you want to base one object off of another (like a time stamp from a date time) a constructor seems natural.

Hope this helps, TJB

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top