0

I'm writing a routine in C# that is designed to copy an object after casting into the object that contains the routine.

Sample Code:

public void SetObjectData(object objectInDisguise)
        {
            Member objectToCopy = (Member)objectInDisguise;

            _field1 = objectToCopy._field1;
            _field2 = objectToCopy._field2;
        }

Null pointer exceptions and weak variable names notwithstanding, is there any way that I can simply cast the object to the Member class and copy the reference to this into my current Member object?

I tried something like:

this = objectToCopy;

but this is read-only, so the compiler didn't let me. Just wondering if anyone knew how one could manage this.

Archer
  • 492
  • 1
  • 4
  • 12
  • In short, no. You can't reassign `this` and it really wouldn't make sense to. If `objectInDisguise` is a `Member` object, you should be able to call all it's methods and access all it's properties anyway. – Matt Burland Jun 18 '14 at 16:38
  • There is no language that allows overwriting the `this` from that I know. Also, it is unclear what you are trying to achieve. Do you want to set member variables from another object that has the same type as your object? Are you trying to copy random objects? Is the copy constructor what you are after? http://stackoverflow.com/questions/3345389/copy-constructor-versus-clone – Mare Infinitus Jun 18 '14 at 16:42
  • 1
    @MareInfinitus: Well C# allows it in a `struct`... – Jon Skeet Jun 18 '14 at 16:44
  • 1
    Fair enough Jon. It should be *"there is no language which allows overwritting of `this` in classes..."* then – Mare Infinitus Jun 18 '14 at 16:46

0 Answers0