c 1 introduction to programming and the c language

c 1 introduction to programming and the c language


DisciplinaFísica Básica I826 materiais10.228 seguidores
Pré-visualização50 páginas
both the class A and the class B. There are several reasons why it is not possible. 
Firstly, there are difficulties in implementing the concept in a programming language in a meaningful 
way, and secondly, one can discuss whether it is an appropriate design, as it expresses that C is both 
an A and B. There are examples where it is reasonable, and in C# a class can inherit a single class, but 
implement all the interfaces, it may have wanted or needed. You\u2019ll have seen many examples of that later.
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
132 
Static members
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\u2019s 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 \u2013 an object of type Random \u2013 
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\u2019t override a static constructor \u2013 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();
}
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
134 
Static members
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(&quot;1234567890&quot;, 8));
Console.WriteLine(Str.Cut(&quot;1234567890&quot;, 12));
}
static void Test2()
{
Console.WriteLine(Str.FillRight(&quot;abc&quot;, 10, 'x'));
Console.WriteLine(Str.FillLeft(&quot;abc&quot;, 10, 'x'));
Console.WriteLine(Str.FillCenter(&quot;abc&quot;, 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(&quot;1234567890&quot;, 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\u2019t 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\u2019t change state \u2013 you can\u2019t 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.
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
136 
Static members
It\u2019s 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\u2019s 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