I have a generic method that copies values between value types. The following approaches give a design time error, even with the struct constraint. Any idea how I can copy or cast between the values?
private Ttgt MyMethod<Tsrc,Ttgt>(Tsrc SourceObject) where Tsrc : struct where Ttgt : struct { //Error:cannot implictly convert type 'Tsrc' to 'Ttgt' Ttgt returnObject = SourceObject; //Error:Cannot convert type 'Tsrc' to 'Ttgt' Ttgt returnObject = (Ttgt)SourceObject; return returnObject; }
Given that there is a registered type converter for the types that you’re trying to convert between a little reflection magic could do the trick:
But out of the box it would be of very limited use since there is no converter between bool and int for example. What problem are you trying to solve?
I also discovered another question with some crazy conversion code in it.
Edit: Your comment makes it clear that you are trying to perform object to object mapping between domain objects and some kind of view/contract model. Have you looked at AutoMapper?