jaydeep more jaydeep more - 1 month ago 7
C# Question

call a nonstatic method of class without initializing it using delegates and events

The question is if there is class

A:show1()
and there is class
B:show()

I have to call
show1()
in class B without using class A object using delegates and events I have tried following:

public class classA
{
private classB _Thrower;

public classA()
{
_Thrower = new classB();
_Thrower.ThrowEvent += (sender, args) => { show1(); };
}

public void show1()
{
Console.WriteLine("I am class 2");
}
}

public class classB
{
public delegate void EventHandler(object sender, EventArgs args);

public event EventHandler ThrowEvent = delegate { };
public classB()
{
this.ThrowEvent(this, new EventArgs());
}
public void show()
{
Console.WriteLine("I am class 1");
}
}


Sorry for any mistakes in question this is my first time of stackoverflow

EDIT:

main()
classB ob=new classB();
classA ob1=new classA();
ob.show();
//on this call the method show1() should be called in classB
//or vice-versa
//output
// I am class A
// I am class B

Answer

To get the result from your edited question you can use this code:

static void Main()
{
    classA obA = new classA();
    classB obB = new classB();
    obA.Shown += ( object sender, EventArgs e ) => { obB.ShowB(); };
    obA.ShowA();
}

public class classA
{
    public event EventHandler Shown;

    public classA()
    {
    }

    public void ShowA()
    {
        Console.WriteLine( "I am class A" );

        if( Shown != null )
            Shown( this, EventArgs.Empty );
    }
}

public class classB
{
    public event EventHandler Shown;

    public classB()
    {
    }

    public void ShowB()
    {
        Console.WriteLine( "I am class B" );

        if( Shown != null )
            Shown( this, EventArgs.Empty );
    }
}

In main() method you could do it vica versa as well:

obB.Shown += ( object sender, EventArgs e ) => { obA.ShowA(); };
obB.ShowB();

But you should not do both at the same time or you'll get an infinite loop ending up in a stackoverflow