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 written 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 an 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.
reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different. It does not check if the pointer type and data pointed by the pointer is same or not.
The reinterpret_cast allows the pointer to be treated as an integral type. The result is then bit-shifted and XORed with itself to produce a unique index (unique to a high degree of probability). The index is then truncated by a standard C-style cast to the return type of the function.
C-style casts can be used to convert any type into any other type, potentially with unsafe results (such as casting an integer into a pointer type). (<type>)<value> This example casts an int to a double for the purpose of avoiding truncation due to integer division: double result = (double)4/5; Popular pages.
The reinterpret_cast operator performs potentially unsafe type casts. It is most often used to cast a pointer to a different pointer type. Casting a pointer to a different pointer and back is usually safe and yields the original value.
This works. And yes, it's as evil and as awesome as you can possibly imagine.
static unsafe TDest ReinterpretCast<TSource, TDest>(TSource source)
{
var sourceRef = __makeref(source);
var dest = default(TDest);
var destRef = __makeref(dest);
*(IntPtr*)&destRef = *(IntPtr*)&sourceRef;
return __refvalue(destRef, TDest);
}
One thing to note is that if you're casting a T[]
to and U[]
:
T
is bigger than U
, the bounds-checking will prevent you from accessing the U
elements past the original length of the T[]
T
is smaller than U
, the bounds-checking will let you read past the last element (effectively its a buffer overrun vulnerability)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With