Getting rid of "static" references in C#
Posted
by DevEight
on Stack Overflow
See other posts from Stack Overflow
or by DevEight
Published on 2010-03-24T09:29:31Z
Indexed on
2010/03/24
9:33 UTC
Read the original article
Hit count: 244
Hello. I've recently begun learning C# but have encountered an annoying problem. Every variable I want available to all functions in my program I have to put a "static" in front of and also every function. What I'd like to know is how to avoid this, if possible?
Also, small side question: creating public variables inside functions?
This is what my program looks like right now, and I want to basically keep it like that, without having to add "static" everywhere:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.Net.Sockets;
namespace NetworkExercise
{
class Client
{
public IPAddress addr;
public int port;
public string name;
public Thread thread;
public TcpClient tcp;
public NetworkStream stream;
public Client(IPAddress addr, int port, string name, NetworkStream stream)
{
}
}
class Program
{
//NETWORK
TcpListener tcpListener;
Thread listenThread;
ASCIIEncoding encoder = new ASCIIEncoding();
//DATA
byte[] buffer = new byte[4096];
string servIp;
int servPort;
//CLIENT MANAGEMENT
int clientNum;
static void Main(string[] args)
{
beginConnect();
}
public void beginConnect()
{
Console.Write("Server IP (leave blank if you're the host): ");
servIp = Console.ReadLine();
Console.Write("Port: ");
servPort = Console.Read();
tcpListener = new TcpListener(IPAddress.Any, servPort);
listenThread = new Thread(new ThreadStart(listenForClients));
listenThread.Start();
}
public void listenForClients()
{
tcpListener.Start();
Console.WriteLine("Listening for clients...");
while (true)
{
Client cl = new Client(null, servPort, null, null);
cl.tcp = tcpListener.AcceptTcpClient();
ThreadStart pts = delegate { handleClientCom(cl); };
cl.thread = new Thread(pts);
cl.thread.Start();
}
}
public void handleClientCom(Client cl)
{
cl.stream = cl.tcp.GetStream();
}
}
}
© Stack Overflow or respective owner