This is not casting problem you encountered. It is mapping problem. For this kind of problems use AutoMapper (it is common problem if you working with database+webservice infrastructure, and is commonly used practice):
using System;
using AutoMapper;
public class Foo
{
public string A { get; set; }
public int B { get; set; }
}
public class Bar
{
public string A { get; set; }
public int B { get; set; }
}
public class Program
{
public static void Main()
{
Mapper.CreateMap<Foo,Bar>();
var foo = new Foo { A="test", B=100500 };
var bar = Mapper.Map<Bar>(foo);
Console.WriteLine("foo type is {0}", foo.GetType());
Console.WriteLine("bar type is {0}", bar.GetType());
Console.WriteLine("foo.A={0} foo.B={1}", foo.A, foo.B);
Console.WriteLine("bar.A={0} bar.B={1}", bar.A, bar.B);
}
}
PS
Actually, there exist a little hack in C#. It is possible to cast one structure to another by aligning fields in stack. Here how it can be done:
[StructLayout(LayoutKind.Explicit)]
public struct MyStructHack
{
[FieldOffset(0)]
public Foo a;
[FieldOffset(0)]
public Bar b;
}
public struct Foo { public int foo; }
public struct Bar { public int bar;}
var convert = new MyStructHack();
convert.a = new Foo {foo = 3};
var bar = convert.b;
Console.WriteLine(bar.bar);
Bear in mind that it is neccessary to have same byte orders in your structures. This techique commonly used because it is faster than doing C# casting. It just skips many language protection checks.