Unless the two types share an inheritance relationship, a common interface, or one of the types provides a conversion operator to the other ... no.
You're going to have to provide some additional details, if you want more specific advice, but here's a general rundown of casting behavior in C#.
Casting in C# can be either a representation preserving operation or a representation changing one. When you cast an instance to a wider or narrow type in it's inheritance heirarchy, or to an interface it implements, you are performing a representation preserving conversion. You're still dealing with the same bits, the compiler/runtime just ensure that the type you specify is valid for the instance of the object you are dealing with. Casts across inheritance heirarchies or to interfaces not implemented by the instance are illegal.
For custom types, representation changing casts are those that essentially create a new instance from an existing one. You can define your own cast operators for a type:
public class MyType
{
public static int implicit operator int( MyType t )
{
return 42; // trivial conversion example
}
}
Conversion operators may be defined as either implicit
or explicit
- which determines whether the compiler will choose to apply them for you (implicit) or will rquire you to explicitly cast the type when you want a converion (explicit).
Given what you describe, you probably need to write a utility class that performs a conversion from one type to another. Unforunately, there's nothing built into C# or .NET that can do this for you.