mrTr0ut
mrTr0ut

Reputation: 61

referencing other class methods without creating a new instance

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

Answers (4)

Cheng Chen
Cheng Chen

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

Jens
Jens

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

npinti
npinti

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

cdhowie
cdhowie

Reputation: 169143

Presumably you would either:

  1. Create the object from the code that creates and shows both forms, and pass a reference to that same instance to both forms, or:
  2. If you create the second form from inside the first form, pass a reference to the instance referenced by the first form to the second somehow (via a property or a constructor, for example).

Upvotes: 1

Related Questions