I’m going to change my C# style in programming(I’ve been using ‘public static’ for variables,methods – everything).
My question:
public class WinSock
{
public Socket sock;
public byte[] data;
.....
}
var data = new byte[2058];
data = WinSock.data;
or this one:
private class WinSock
{
private Socket sock;
private byte[] data;
.....
public byte[] getdata()
{
get {return data;}
}
}
WinSock ws = new WinSock();
var data = new byte[2058];
data = ws.getdata();
In both cases the data and sock variables can be accessed from other classes.
Which of the two declarations is better?
The second one is closer to what’s generally considered to be better. In Object Oriented Programming we encapsulate the variables in the classes and only expose as little as needed outside the class.
Name your properties with an initial capital letter, and as a data member rather than a method, i.e.
Datarather thangetdata.(One way to name the private member variables is to use an underscore. There are some other conventions commonly used, but the important thing is really to pick one and stick to it.)
In C# 3 there is also a shortcut syntax for properties: