Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use the Singleton pattern to assure that only one instance is ever created. </p> <p>However, <a href="https://stackoverflow.com/questions/11831/singletons-good-design-or-a-crutch">the jury is still out</a> (at least in my mind) on whether this is a good decision. There's plenty of reading on SO and other places about this.</p> <p>I would approach this from a different angle. I'd make all of my forms take in a Person instance in the constructor. That way, each form is only ever worried about it's instance of Person. </p> <p>You could do this by creating a new class that inherits from Form and has a field/property/constructor for your Person. Then, any form that uses Person can inherit from your new class.</p> <p>You would, of course, have to manage the creation of your Person object. You could even do this with a singleton. However, the benefit is that each form doesn't have to know how to create a Person or who created the Person. That way, if you choose to <a href="https://stackoverflow.com/questions/474613/how-should-i-refactor-my-code-to-remove-unnecessary-singletons">move away from the Singleton pattern</a>, you wouldn't have to go change all of your references to your singleton instance.</p> <p><strong>EDIT:</strong></p> <p>Here's some code to demonstrate this. It took me a while to get the designer to play nice. I had to add an empty private constructor in PersonForm to get the designer to not throw an error.</p> <p>Program.cs</p> <pre><code>static class Program { /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MyDerivedForm(new Person { Name = "Hello World!" })); } } </code></pre> <p>Person.cs</p> <pre><code>public class Person { public virtual string Name { get; set; } } </code></pre> <p>PersonForm.cs</p> <pre><code>using System; using System.Windows.Forms; public class PersonForm : Form { private readonly Person myPerson; protected virtual Person MyPerson { get { return this.myPerson; } } private PersonForm() { } public PersonForm(Person person) { this.myPerson = person; } } </code></pre> <p>MyDerivedForm.cs (add a label named label1)</p> <pre><code>public partial class MyDerivedForm : SingletonMadness.PersonForm { public MyDerivedForm(Person person) : base(person) { InitializeComponent(); } private void MyDerivedForm_Load(object sender, EventArgs e) { label1.Text = this.MyPerson.Name; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload