views:

361

answers:

5

I have made the Graph class, and i want to simulate a distribution network. The Graph works 100%. But, i want to use that same struct/class in all my application! For example: I have Form1 that shows the simulation, but i want to insert Nodes (for example) but i want to do it in Form2! Since the data is always in the same class, i could make my Graph instance global but C# does not take global variables. So, how would i solve this? Any ideas? Thank you!

+4  A: 

Give the forms a reference to the Graph in their constructor.

 Graph g = new Graph();
 Form1 f1 = new Form1(g);
 Form2 f2 = new Form2(g);

Then both forms are working with the same graph.

Matt Greer
OP here,So your saying that f1 and f2 have the SAME graph? not a copy?
Ricardo
They each have different **references** to the same graph, but yes, it's the same graph.
John Feminella
thank you very much!
Ricardo
Other people are recommending the Singleton pattern. However, I recommend caution with that pattern, as it can be a crutch and it can really hamper your code in the long run. Not saying singleton pattern is always bad, but it's a difficult pattern to use correctly.
Matt Greer
Problem is solved! I thought that would generate a copy of the instance, but it really passes the SAME instance to both forms.
Ricardo
Both f1 and f2 got different references that lead them to the same object.
Matt Greer
A: 

C# has static fields for this. You can use SIngleton pattern in conjunction with static field. But don't forget that misusage of application-wide objects can bring down your design.

Vitaliy Liptchinsky
+2  A: 

Make your Graph instance a public static member of a static class and for all practical purposes you have your global.

Nemanja Trifunovic
+2  A: 

Take a look at the Singleton pattern for one possible approach to having a common object:

Singleton Pattern

Peter Loron
+4  A: 

Make a static class. The variables that need global access, put them inside that class.

Even better idea would be to use Singleton objects to represent globally accessible objects.

missingfaktor
Note that either solution will cause all consumers to be tightly coupled to the Graph class. Among other things, this will make it difficult to test those consumers in isolation.
TrueWill