views:

81

answers:

3

Hello,

In Silverlight / C#, I have class Main, which creates an instance of Child, Child _child = new Child(...)

Now, in Child class I need to call a method from Main class. What should be the best way to do this ? Events?

+3  A: 

Eventing is the proper pattern. See this answer on the conceptual reasons around information flow in an object/class hierarchy.

deeper components simply "release" their information - usually via an event - and it "floats" up the chain without directly invoking

Rex M
+7  A: 

Simplest solution will be to provide a reference to Main to an instance of Child class:

public class Child
{
    private Main main;

    public Child(Main main)
    {
        this.main = main;

        main.Bar();
    }
}

public class Main
{
    public void Foo()
    {
        Child c = new Child(this);
    }

    public void Bar()
    {
    }
}

This can be further improved by abstracting away Main class behind a IMain interface in order to minimize coupling.

But best solution will be to utilize event bubbling

Anton Gogolev
+4  A: 

The answer depends upon what the semantics of the call are; your example is vague and has no obvious semantics to reason from, so it is impossible to give a good answer.

Is Main providing a service to Child? For example, is the call that Child wants to do on Main something like "get me the list of users who are authorized to do blah", or "add up all the accounts receivable for November"?

Or is Main reacting to an event assocaited with Child? For example, perhaps Child is a button and Main is a form, and Main wishes to react when the button is clicked.

In the former case, Main should provide an object -- possibly itself -- to Child that implements the desired service. The object might be Main itself, or a delegate to a method, or an interface, but it's something that Child can invoke when the service is needed.

In the latter case, Main should listen to the event raised by Child.

Which is correct depends on the meaning of the objects; can you describe the meaning more clearly?

Eric Lippert
Main is the MainPage, an user control. Child is a class which represents an object in scene. I want to call a method of Main from child, which changes some MainPage parameters. The call is dependent of user interaction
jose