Reputation: 2184
I have a couple of reusable methods GetChartData() and GetPeopleData(). They are stored in a controller called CentralData.cs
I would like to be able to call any one of these methods from a different controller but I'm not sure how I would do that. Does anyone know how I call a method that is located in another controller?
If the method was in the same class it would be as simple as:
MyMethod()
{
GetChartData();
}
So if the method is in a different controller and as sucha different class, how do I call it?
Upvotes: 0
Views: 2639
Reputation: 804
If you mean that you have 2 controller classes: Controller
and OtherController
, then you can access a method located in the second class from the first class like this:
class Controller
{
public void MethodA()
{
OtherController.MethodB(); // This will work because MethodB is static
// Like shown above you can call a static method from anywhere
}
}
class OtherController
{
public static void MethodB() // <-- Notice "static"
{
// Do stuff
}
}
I hope this is what you were looking for and that this was a sufficient explaination. If I am too unclear, then just ask what's confusing.
Upvotes: 0
Reputation: 443
You can only call a non-static method from another class if you have a reference of the object.
If you create the second controller somewhere in the first controller, like:
ButtonClick(object Sender, EventArgs e) {
CentralData c = new CentralData();
}
you can simply save that reference in a private variable and lateron say
MyMethod()
{
c.GetChartData();
}
If you create both of them in another class you have to pass the CentralData object to your other Controller like
public static void Main() {
CentralData c = new CentralData();
WindowController w = new WindowController(c);
}
or
public static void Main() {
CentralData c = new CentralData();
WindowController w = new WindowController();
w.c = c;
}
Upvotes: 0
Reputation: 1605
You can create an object of Controller
and call the function like a simple class. I do not think any problems with this approach. After all, a controller is just a class.
e.g.,
MyController obj = new MyController();
obj.MyFunction();
Upvotes: 1