Reputation: 439
I'm trying to pass data from one instance of a class to another instance of a class - i.e. call a method (non-static) belonging to one class from another.
For simplicity's sake I'll make up the code here, but the principle will still be the same.
Our first class will be called class1 and our second class2. Class1 will be trying to call a method within class2 called myMethod which takes parameters: int i.
Here's the code:
namespace myNamespace
{
static void Main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
}
public class Class1
{
public Class1()
{
class2.myMethod(5);
}
}
public class Class2
{
private int myInt;
public myMethod(int i)
{
myInt = i;
}
}
}
Now I can see some obvious problems in the code. Firstly there isn't an instance of Class2 for Class1 to pass the data to... However due to the nature of my program this has to be how it's done. (Class2 runs a loop meaning no code beyond it gets run)
A possible fix to this would be to have myMethod being static but then there's the problem of passing data from the static method to a non-static variable.
I'm not well read on interfaces, could this be the best fix? I also thought I might be able to write data from class1 into a file and then have class2 read and remove the data from the file during it's loop... but this seems a bit tedious.
So how should I be passing the data / calling the method?
Thanks for the help.
Upvotes: 1
Views: 666
Reputation: 101681
You can try to change your Class1
constructor like this:
public Class1(Class2 c2)
{
c2.myMethod(5);
}
Then pass your Class2
instance into your Class1
constructor:
Class2 c2 = new Class2();
Class1 c1 = new Class1(c2);
Upvotes: 3
Reputation: 4727
I'm not sure that I understand your requirement, but the simpliest way would be to pass the instance of Class2
to the constructor of Class1
:
public Class1(Class2 c2)
{
c2.myMethod(5);
}
Then you can call your classes as follow:
Class2 c2 = new Class2();
Class1 c1 = new Class1(c2);
Upvotes: 0
Reputation: 1038830
I'm not well read on interfaces, could this be the best fix?
No, not at all, interfaces have nothing to do here.
I also thought I might be able to write data from class1 into a file and then have class2 read and remove the data from the file during it's loop... but this seems a bit tedious.
Hmmm, not sure I understand.
So how should I be passing the data / calling the method?
In OOP you have 2 possibilities to invoke a method:
Upvotes: 0