Reputation: 61
I have a class by itself called clientChat
that does basic network stuff. I have several other classes linked to different window forms. In my first form I have a variable referenced to the chat class like so:
clientChat cc = new clientChat();
Everything works okay their, the class has been initialized and everything is in motion. After the first forms is done performing it's duty I bring up my second form that's obviously linked to a new class file.
Now my question is, how can I reference what's going on in the clientChat
class without setting a new instance of the class? I need to pass data from the form to the networkstream
and if I create a new instance of the class wouldn't that require a new connection to the server and basically require everything to start over since it's "new"? I'm a bit confused and any help would be great, thanks. C# on .NET4.0
Upvotes: 6
Views: 3154
Reputation: 43523
In additional to @Jens's answer, there are 5 approaches on the linked page, while I think we have the 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;
}
}
}
Upvotes: 0
Reputation: 25573
You may want to look into the Singleton design pattern. Mr Skeet has written a good article on how to implement it in C# here. (Just use version 4. its the easiest and works fine =) )
Upvotes: 2
Reputation: 52185
You could create an instance of clientChat
in the beginning of your program and then, simply pass its reference to the classes that need it.
Upvotes: 2
Reputation: 169143
Presumably you would either:
Upvotes: 1