Calling "Form" class method from "A" class without adding a reference to the "Form" class

1.3k views Asked by At

I have two Projects one is a Winform application another is a Class library. I have added a reference to the class Library in Winform and called a method of the class library. Now I want to call a different method in winform application from class library but I can't add a reference to winform to the class library.

IN CODE:-

public partial class Form1 : Form
    {
        private void btn_Click(object sender, EventArgs e)
        {
            A obj = new A();
            obj.foo();
        }
        public string Test(par)
        {
            //to_stuff
        }


    }

and in Class library

 class A
    {
        public void foo()
        {
            //Do_stuff
            //...

            Test(Par);

            //Do...

        }
    }
2

There are 2 answers

6
David Arno On BEST ANSWER

You can achieve this by injecting Test into class A.

For example:

public partial class Form1 : Form
{
    private void btn_Click(object sender, EventArgs e)
    {
        A obj = new A();
        obj.foo(Test);
    }

    public string Test(string par)
    {
        //to_stuff
    }
}

class A
{
    public void foo(Func<string, string> callback)
        //Do_stuff
        //...

        if (callback != null)
        {
            callback(Par);
        }

        //Do...

    }
}
0
Jürgen Steinblock On

While the callback method from David is a sufficient solution, if your interactions gets more complex, I would use this approach

Create an inteface in your class libary

public interface ITester
{
    string Test(string value);
}

Rewrite your code so class A expects an ITester interface

public class A
{
    public A(ITester tester)
    {
        this.tester = tester;
    }

    public string foo(string value)
    {
        return this.tester.Test(value);
    }        
}

Implement your interface in Form1

public partial class Form1 : Form, ITester
{
    private void btn_Click(object sender, EventArgs e)
    {
        A obj = new A(this);
        obj.foo("test");
    }

    public string Test(string value)
    {
        //to_stuff
        return value;
    }
}