Changing the type of instantiate object in C #


Consider these classes:

class ClassA
    public int x;

class ClassB : ClassA
    public int y;

then, somewhere in the code I instantiate a new ClassA:

var o = new ClassA();
var anotherRef = o;

This mean I'm getting a chunk of memory with size sizeof(ClassA) (say 4 bytes) starting in an address like 0x100.

Then somewhere I decide to change the type of o to ClassB and add the value of y. So I want the o still address to 0x100 but with size of sizeof(ClassB) (say 8 bytes).

SomeMagicToChangeType(o, new ClassB());
// Now anotherRef should be a ClassB

In this case it will be good for anotherRef since it will reference to a correct instance.

Is it possible to do something like this in C#?

In short: no, you cannot do this in C#.

  1. You cannot assign a ClassB to o as it is strongly typed to ClassA.
  2. (without getting really hacky) you cannot control memory allocations or locations in C#.

If you want to do this sort of trickery, you'll need another language other than C#.