discussion
As some answers point out, .Net strictly adheres to type safety within the scope of the question. reinterpret_cast will be an unsafe operation, so the possible ways to implement it are either reflection or serialization, while both are interconnected.
As you mentioned in the update, a possible use could be an RPC structure. RPC libraries usually use serialization / reflection anyway, and there are a few useful ones:
so you may not want to write it yourself.
If your Base class will use public properties, you can use AutoMapper :
class Base { public int Counter { get; set; }
...
AutoMapper.Mapper.CreateMap<Base, Foo>(); Foo foo = AutoMapper.Mapper.Map<Foo>(b);
Where Foo does not need to be extracted from Base . It just needs to have the property that you are interested in displaying. But then again, you may not need two types at all - rethinking the architecture may be the solution.
Typically, there is no need to use reinterpret_cast as a clean architecture that fits well with the templates used in the .Net Framework. If you still insist on having something like this, here is a solution using the compact protobuf-net serialization library.
serialization solution
Your classes:
using System; using System.IO; using ProtoBuf; using ProtoBuf.Meta; [ProtoContract] [ProtoInclude(3, typeof(Foo))] class Base { [ProtoMember(1)] protected int counter = 0; public Base(int c) { counter = c; } public Base() { } } [ProtoContract] class Foo : Base { public int Counter { get { return counter; } } }
and a working example of serialization-deserialization:
class Program { static void Main(string[] args) { Base b = new Base(33); using (MemoryStream stream = new MemoryStream()) { Serializer.Serialize<Base>(stream, b); Console.WriteLine("Length: {0}", stream.Length); stream.Seek(0, SeekOrigin.Begin); Foo f=new Foo(); RuntimeTypeModel.Default.Deserialize(stream, f, typeof(Foo)); Console.WriteLine("Foo: {0}", f.Counter); } } }
Output
Length: 2 Foo: 33
If you do not want to declare derived types in your contract, see this example ...
As you can see, serialization is extremely compact.
If you want to use more fields, you can try implicit field serialization:
[ProtoContract(ImplicitFields = ImplicitFields.AllFields)]
The universal reinterpret_cast , of course, can be implemented either using this serialization solution or directly using reflection, but I would not waste time at the moment.