Mehran Mehran - 4 years ago 217
C# Question

Equivalent of C++'s reinterpret_cast in C#

I wonder what's the equivalent of C++'s

reinterpret_cast
in C#!?

Here's my sample:

class Base
{
protected int counter = 0;
}

class Foo : Base
{
public int Counter
{
get { return counter; }
}
}

Base b = new Base();
Foo f = b as Foo; // f will be null


I've got no objection why
f
will be null since it should be. But if it was C++ I could have wrote
Foo f = reinterpret_cast<Foo>(b);
and get what I wanted. What can I do to achieve the same in C#?

PS. I'm assuming that
Base
and
Foo
are consistent data-wise.


[UPDATE]

Here's a simple scenario where a
reinterpret_cast
could be helpful:

Consider writing a XXX-RPC library where you've got no control over the incoming parameters nor the signature of services to call. Your library is supposed to call the asked service with the given parameters. If C# supported
reinterpret_cast
I could simply
reinterpret_cast
the given parameters into the expected ones and call the service.

Answer Source

discussion

As some of the answers point out, .Net is enforcing type safety rigorously in the question's scope. A reinterpret_cast would be an inherently unsafe operation, hence the possible ways to implement one would be either through reflection or serialization, whereas the two are related.

As you mentioned in an update, a possible use could be an RPC framework. RPC libraries typically use serialization/reflection anyway, and there are a couple of usable ones:

so, you might not want to write one yourself, perhaps.

If your class Base would use public properties, you could use AutoMapper:

class Base
{
    public int Counter { get; set; }
    // ...
}

...

AutoMapper.Mapper.CreateMap<Base, Foo>();
Foo foo = AutoMapper.Mapper.Map<Foo>(b);

Where Foo need not be derived from Base at all. It just has to have the property you are interested in mapping onto. But again, you might not need two types at all - a rethinking of the architecture might be the solution.

Typically, there is no need to use reinterpret_cast, by way of a clean architecture that fits nicely into the patterns used in the .Net Framework. If you still insist on having something like that, here's a solution using the compact serialization library protobuf-net.

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 runnable serialization-deserialization example:

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);
        }
    }
}

outputting

Length: 2
Foo: 33

If you don't want to declare derived types in your contract, see this example...

As you see, the serialization is extremely compact.

If you want to use more fields, you might try implicit serialization of fields:

[ProtoContract(ImplicitFields = ImplicitFields.AllFields)]

A generic reinterpret_cast might definitely be possible to implement either via this serialization solution, or directly via reflection, but I wouldn't invest the time at the moment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download