0

Say I have these Classes and variables

public class Human {
    public string name;
}

public class Home {
    public Human m_oHuman = null;

    public Home(ref Human p_oHuman) { //note the ref
        m_oHuman = p_oHuman;
    }

    //p_oNewHuman takes over the home
    public void TakeOver(Human p_oNewHuman) { //don't need ref, just need copy
        m_oHuman = p_oNewHuman; //Won't work as intended.
    }
}

//Run this code
public Human homeOwner = new Human { name = "Sally" };
public Home home = new Home(ref homeOwner)
public Human homeStealer = new Human { name = "Daisy" };
home.TakeOver(homeStealer);

What I'm trying to do is pass homeOwner by reference and save that reference in the global variable m_oHuman then later I want to try make homeOwner "point" to homeStealer or at least a copy of homeStealer since it's not passed by ref. But doing it the way I've coded seems to make m_oHuman lose the initial reference, and so homeOwner is still "Sally" when I want it to point to p_oNewHuman.

What I'm thinking I must do, instead of m_oHuman = p_oNewHuman;, is go through and copy all the variables from p_oNewHuman to m_oHuman.

But with the code I'm really working with, there are many members and classes that I'm trying to make work like the code above and I feel this could become cumbersome having to manually copy object variables. So I'm wondering if there was a better or easier way to achieve this goal.

mrwindigo
  • 1
  • 1
  • There are no "global variables" in C#. `TakeOver` just replaces the reference, stored in `m_oHuman` field, to the new one, passed as `TakeOver` method parameter. Also, you're misunderstanding, how `ref` keyword works. – Dennis Feb 24 '16 at 08:08
  • You would need `m_oHuman` to be a `ref` also but that's not allowed. Not just "not allowed in C#" but also "not allowed by the CLR". – Damien_The_Unbeliever Feb 24 '16 at 08:10

0 Answers0