Exam33 Points again
15 Static members
I would like once again to look at static members in a class. Both variables and methods can be static, and indeed can a class be static.
When you create an object of a class, you create simultaneously the data elements as simple variables and other objects that the class’s instance variables define. Each object of the class has its own copy of all instance variables, and if an object changes the value of an instance variable it only concerns the object itself.
Things are different with static variables as a static variable is created only for the first time an object of the class is created. This means that all objects created from the same class share a static variable, or said differently that a static variable is not tied to a particular object.
A good example of using a static variable is a random number generator – an object of type Random – as in the classes Coin and Dice. Here it is important that all objects (for example all Dice objects) are using the same random number generator. The static random number generator is initialized in the declaration of the static variable:
private static Random rand = new Random();
It is not always possible or desirable, and one can instead initialize static variables in a static constructor that has no other purpose than to initialize static variables. For example you could write the class Dice, as follows:
public class Dice {
private static Random rand; private int oejne;
static Dice() {
rand = new Random(); }
There is no justification for it in this case, but a static constructor is executed the first time a program creates an object of the class. You can’t override a static constructor – there are no options to transfer parameters.
Also, methods can be static. If you have a static method, you can use it without having an object of the class, and the method is referenced by setting the class name before method name.
Download free eBooks at bookboon.com
Click on the ad to read more
C# 1 Introduction to programming and the C# language
133
Static members
Exam34
StringBuilder
In this example I will show a class that contains only static methods. The class will consist of methods to manipulate the strings, and is a class which may be useful in practice. I should also mention the class
StringBuilder, a class that can give increased efficiency in situations with many operations on strings. Finally, the example has a test program that tests the class.
How to
The starting point is a class Str with 4 static methods:
public static class Str {
public static string Cut(string text, int width) {
if (text.Length > width) return text.Substring(0, width); return text;
}
public static string FillRight(string text, int width, char ch) {
StringBuilder builder = new StringBuilder(text); while (builder.Length < width) builder.Append(ch); return builder.ToString();
}
“The perfect start
of a successful,
international career.”
CLICK HERE
to discover why both socially and academically the Universityof Groningen is one of the best places for a student to be
www.rug.nl/feb/education
public static string FillLeft(string text, int width, char ch) {
if (text.Length >= width) return text;
StringBuilder builder = new StringBuilder(width - text.Length); for (int i = 0; i < builder.Capacity; ++i) builder.Append(ch); return builder.ToString() + text;
}
public static string FillCenter(string text, int width, char ch) {
return FillRight(FillLeft(text, text.Length + (width - text.Length) / 2, ch), width, ch);
} }
In this case, the class Str is located in its own file. This provides better opportunities to use the class in other programs.
Below is a test program:
class Program {
static void Main(string[] args) {
Test1(); Test2(); }
static void Test1() {
Console.WriteLine(Str.Cut("1234567890", 8)); Console.WriteLine(Str.Cut("1234567890", 12)); }
static void Test2() { Console.WriteLine(Str.FillRight("abc", 10, 'x')); Console.WriteLine(Str.FillLeft("abc", 10, 'x')); Console.WriteLine(Str.FillCenter("abc", 10, 'x')); } }
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language
135
Static members
Explanation
The first method cut of the string, so that it has a maximum width (number of characters):
public static string Cut(string text, int width) {
if (text.Length > width) return text.Substring(0, width); return text;
}
It is a static method (in fact a very simple but useful method), and it may, for example be used as follows:
Console.WriteLine(Str.Cut("1234567890", 8));
You should note that the method referenced by typing class name Str in front.
Basically, a static method can do the same as other methods, and it is important that it can be used without an object. In turn, a static method can’t refer to instance variables, but there are also many examples of methods, that does not. A good example is the Math class, which contains a number of mathematical functions. They are all implemented as static methods.
The second method is a method that extends a string to a minimum width, such that it is filled out to the right with a specific character ch. The method uses a StringBuilder, but it could be written differently:
public static string FillRight(string text, int width, char ch) {
while (text.Length < width) text += ch; return text;
}
A string object can’t change state – you can’t change the content of a string. If you look at the expression
text += ch;
it means to create a string object that contains the previous content of text and expanded it with value
ch. That means, the creation of an object on the heap, and the old string have to be copied to it. In most cases it is not essential, but if there is to be added number of filler characters corresponding to the loop is repeated many times, it may affect the performance and be detectable. It is here the type StringBuilder
comes into the picture. There is a kind of buffer for characters that can expand dynamically and when needed. The statement
StringBuilder builder = new StringBuilder(text);
creates a new StringBuilder with the content of text. The second loop adds the characters until the builder contains the desired number of characters, and note that it automatically expands as needed.
It’s hard to say exactly when to use a StringBuilder, but if there are more than 10 extensions you should consider whether it is worthwhile to take this class in use.
The third method is similar to FillRight(), but it fill character in from the left. It also uses a StringBuilder, but the parameter to the builder’s constructor is this time is a number: the number of fill characters to be used. This means that the builder from the start can accommodate the required number of characters, and thus should not be expanded. Note also how, in the loop there are used a property Capacity to determine how many characters to be added.
If one considers the class Str, then all the methods are static. If so, you can also define the class as static:
public static class Str {
If so, it is not possible to create objects of the type Str, and also it gives the no opinion in this case.
Comment
When you in Visual Studio creates a new console application it automatically creates a class with a
Main() method. It is a static method and it must be, as it must be called by the runtime system without having an object. In most testing programs the class with Main() had only static methods, for example.
static void Test2() {
Console.WriteLine(Str.FillRight("abc", 10, 'x')); Console.WriteLine(Str.FillLeft("abc", 10, 'x')); Console.WriteLine(Str.FillCenter("abc", 10, 'x')); }
and the method is usually called from Main(). When you in such situations has no object, the methods must be static, and that is why the methods in the Main() class has always been static.
Download free eBooks at bookboon.com
Click on the ad to read more
C# 1 Introduction to programming and the C# language
137
More about arrays
16 More about arrays
I have previously defined an array as a number of elements of a particular type that can be referenced via a common name. The picture of an array is a structure like the following
0 1 2 3 4 5 6 7 8 9
where each box has room for an element of the arrays type. The individual elements can be referenced using the array name and an index that always starts from 0. The type can be anything, and in the class
Cup it was a Dice, while in the class Purse it was an IBankNote. The only thing to note is that if the type is a value type, the boxes directly contains the value that is attached to the individual indices, but if the type is a reference type, the boxes contains only references to the objects that are linked to the individual objects. It is rare that it means so much in practice, but you should be aware that if you write something like the following
Dice[] t = new Dice[5];
then there is created an array, but there it is not yet filled with Dice objects. The array is empty corresponding to each position contains null. There is not yet created any Dice objects.
An array as above is a 1-dimensional array. One can also work with arrays of multiple dimensions. For example is a 2-dimensional array a structure organized into rows and columns, and each element can be referenced using the array name and an index pair. For example you can define a two-dimensional array of elements of the type int having 4 rows and five columns in the following manner:
int[,] t = new int[4, 5]; t[2, 3] = 43;
This can be illustrated in the figure below. Please note that as with a 1-dimensional array indices start with 0 – for both rows and columns.
43 0 1 2 3 1 2 3 4 0
It is seldom you are using arrays with more than two dimensions, but there is no upper limit to the number of dimensions, but for us humans it is difficult to give the array a geometric interpretation. For example you can define a 3-dimensional array as:
int[,,] t = new int[3, 4, 2];
This can be illustrated as a cube (or more 2-dimensional arrays, lying behind each other):
0
1
2
1
3
0
2
0
1
The individual elements referenced by three indices, for example.
t[1, 2, 1] = 53;
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language
139
More about arrays