1

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#?

6
  • Nope, not really. You can't change the type of an object after creation. C# is a statically typed language. What are you trying to achieve? There'll most likely be a way without doing this. Commented Nov 18, 2013 at 6:42
  • What are you trying to achieve and why are you trying to achieve such thing? When you say address 0x100 it is not fixed. GC have all rights to move it over anytime. Commented Nov 18, 2013 at 6:44
  • @Baldrick I've loaded o from database with type of ClassA, at some place I understand that it's real type is ClassB and that part is in another table. But as software did some work there are another references created. I want update the type of o in a way that the other references don't break. Commented Nov 18, 2013 at 6:45
  • @SriramSakthivel by the address I mean that I want the other references work fine. It's not important if the address changes. But the references must be same. Commented Nov 18, 2013 at 6:47
  • Not possible. I'll suggest you to implement a common interface or abstract class in both classes and use the interface without the concrete type. Commented Nov 18, 2013 at 6:48

2 Answers 2

2

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#.

Sign up to request clarification or add additional context in comments.

Comments

0

I belive you really don't care about memory address, do you?

If so, can you just modify a class B, e.g by adding a ctor

B(A a) {
    this.x=a.x;
}

and then "convert" you A to B in a way:

B converted = new B(yourOldA);

2 Comments

And if you cannot modify B you can create a new class, kind of wrapper (by extending B)
The point of question is to have converted referenced same as a. Your solution is to create a new instance similar to a, not extending the a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.