Reputation: 85
New to C# here. So I got my first class (Form1) and second class (Class1) in different projects. I added Form1 to Class1's references because Form1 had data from its GUI that Class1 needed to make computations from its method. Problem is, I cant get the results from the method in Class1 to Form1 because I can't reference it because of circular reference.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label3_Click(object sender, EventArgs e)
{
}
public void button1_Click(object sender, EventArgs e)
{
// for getting data from Class1
// ClassLibrary1.Class1 c = new ClassLibrary1.Class1();
// label7.Text = c.GetDate(); }
private void button2_Click(object sender, EventArgs e)
{
}
}
public class Class1
{
private int daysz;
private int GetDate()
{
Activity3_Espiritu.Form1 f = new Activity3_Espiritu.Form1();
daysz = (f.lastDay - f.firstDay).Days;
return daysz;
}
}
What's a clean way to get around this? I've tried interfaces but I've absolutely no idea how to use it, even after looking online for solutions.
Upvotes: 0
Views: 517
Reputation: 49985
Class1 should never need a reference to your Form1, instead the code from Form1 should call the GetDate()
method in Class1 and pass in the appropriate parameters for GetDate()
to evaluate. When GetDate()
returns the result you simply assign it to a variable or back into the user control that needs to show it (would that be Label7
?).
public void button1_Click(object sender, EventArgs e)
{
var c = new Class1();
var yourResult = c.GetDate(lastDay, firstDay);
label7.Text = yourResult;
}
public int GetDate(DateTime lastDate, DateTime firstDate)
{
return (lastDate - firstDate).Days;
}
Upvotes: 3
Reputation: 7054
If you can change signature of GetDate
method you can try this code:
public class Class1
{
private int daysz;
private int GetDate(__yourDatType__ lastDay, __yourDatType__ firstDay)
{
daysz = (lastDay - firstDay).Days;
return daysz;
}
}
now, in button1_Click
write this:
ClassLibrary1.Class1 c = new ClassLibrary1.Class1();
label7.Text = c.GetDate(this.lastDay, this.firstDay);
Upvotes: 1