Digital Ape Digital Ape - 3 months ago 9
C# Question

Run method from different scope

I know that what i need help with is not called the Parent but that was the closest word i could think of to describe this situation.

This is not actual code i'm using.

I have

MainClass
which contains object
ObjectA
.

class MainClass
{
public int mode = 0;
ObjectA obj = new ObjectA();

}


I need to access the
mode
variable from the
ObjectA
object. Is this possible? I feel like if i could at least call a method in
MainClass
from
obj
i would be all set. Also I'm aware calling
MainClass
a parent in this sense is incorrect, what is the correct term for both the
MainClass
and
obj
in this.

Answer

Assuming you are able to change MainClass, I can think of two options:

  • Add a reference to MainClass when you create an ObjectA instance.
  • Like you said in your comments, use events.

Using a reference:

class MainClass
{
    public int mode = 31416;
    ObjectA obj;

    public MainClass() 
    {
        obj = new ObjectA(this);
    }

    public int GetMainClassMode() 
    {
        return mode;
    }

    public void Test() {
        Console.WriteLine("Calling test method inside obj");
        obj.Test();
    }
}

class ObjectA {

    MainClass parent = null;

    public ObjectA(MainClass parent) 
    {
        this.parent = parent;
    }

    public void Test() 
    {
        if (parent != null) 
        {
            Console.WriteLine("Getting mode from 'parent' MainClass");
            Console.WriteLine(string.Format("Mode = {0}", parent.GetMainClassMode()));
        }
    }       
}

Using events:

class MainClass
{
    public int mode = 31416;
    ObjectA obj = new ObjectA();


    public MainClass() 
    {
        obj.ValueReturnEvent += HandleValueReturnEvent;
    }

    public int GetMainClassMode() 
    {
        return mode;
    }

    // Handle event, return data
    private int HandleValueReturnEvent(object sender, EventArgs e)
    {
        return mode;
    }

    public void Test() {
        Console.WriteLine("Calling test method inside obj");
        obj.Test();
    }
}

class ObjectA {

    // delegate
    public delegate int ReturnValueEventHandler(object sender, EventArgs args);
    // event
    public event ReturnValueEventHandler ValueReturnEvent;


    public void Test() 
    {
        // make sure at least one subscriber
        if (ValueReturnEvent != null)  
        {
            // note the event is returning a value
            var myValue = ValueReturnEvent(this, null);

            Console.WriteLine("Getting mode from 'parent' MainClass");
            Console.WriteLine(string.Format("Mode = {0}", myValue));
        }
    }   
}

On both cases, you get this output:

Calling test method inside obj
Getting mode from 'parent' MainClass
Mode = 31416
Comments