Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 240
mrTr0ut Avatar asked Nov 16 '10 07:11

mrTr0ut


People also ask

How do you call the method of a class without creating its instance?

Static method(s) are associated with the class in which they reside i.e. they are called without creating an instance of the class i.e ClassName. methodName(args). They are designed with the aim to be shared among all objects created from the same class.

How do you call a method from another class without creating an object?

We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.

Can we access data of class without creating instance?

You can access class even without making any object . We normally make instances to use the methods and the attributes of the class.

How do you call a method from another class without creating an object in Python?

You can however do something else: call a method in a class without creating an object. Demonstration of static method below. Define a class with a method. Add the keyword @staticmethod above it to make it static.


2 Answers

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.

like image 63
npinti Avatar answered Oct 07 '22 05:10

npinti


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 =) )

like image 40
Jens Avatar answered Oct 07 '22 03:10

Jens