Links to other class methods without creating a new instance

I have a class itself called clientChat that does basic networking stuff. I have several other classes related to various forms of windows. In my first form, I have a variable related to the chat class, for example:

 clientChat cc = new clientChat(); 

Everything works fine, the class is initialized, and everything is moving. After the first forms are completed, I will raise my second form, which is obviously associated with the new class file.

Now my question is: how can I refer to what happens in the clientChat class without installing a new instance of the class? Do I need to transfer data from the form to networkstream , and if I create a new instance of the class, it will not require a new connection to the server and basically requires that everything starts from the moment it is "new"? I'm a bit confused and any help would be great, thanks. C # on .NET4.0

+4
source share
4 answers

You can create an instance of clientChat at the beginning of your program, and then simply pass it a link to the classes that need it.

+3
source

You might want to explore the Singleton design template. Mr. Skeet wrote a good article on how to implement it in C # here. (Just use version 4. its simplest and works just fine =))

+3
source

Presumably you would either:

  • Create an object from the code that creates and displays both forms, and pass a link to the same instance for both forms, or:
  • If you are creating a second form from the first form, first pass a link to the instance referenced by the first form, to the second (via a property or constructor, for example).
+1
source

In addition to @Jens answer, there are 5 approaches on the linked page, while I think we have 6th using Lazy<T> in C # 4.0

 public sealed class Singleton { private Singleton() { } private static readonly Lazy<Singleton> m_instance = new Lazy<Singleton>(() => new Singleton()); public static Singleton Instance { get { return m_instance.Value; } } } 
0
source

All Articles