c 1 introduction to programming and the c language

c 1 introduction to programming and the c language


DisciplinaFísica Básica I826 materiais10.230 seguidores
Pré-visualização50 páginas
leader in aerospace, defence and related services.
Let your imagination take shape.
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
73 
Classes
8 Classes
After this rather technical explanation it is time to deal with classes in C#.
Exam22
Coins
You must write a program to simulate that you throw two coins. The program will throw the coins until 
they both show crown (Head). If you run the program, the result could be the following:
How to
There is a need for a type which can represent a coin. In this case, the coin\u2019s value will be head or tail 
and it must provide the following services available:
\u2022	 one should be able to throw the coin (simulating that it gets a random value)
\u2022	 one should be able to read the coin\u2019s value (see what the coin shows)
The type is called Coin and may be illustrated as follows:
Coin
value: char
Value: char
Throw()
The code can be written as follows:
class Program
{
static void Main(string[] args)
{
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
74 
Classes
Coin c1 = new Coin();
Coin c2 = new Coin();
do
{
c1.Throw();
c2.Throw();
Console.WriteLine(c1.Value + " " + c2.Value);
}
while (c1.Value != 'H' || c2.Value != 'H');
}
}
public class Coin
{
private static Random rand = new Random();
private char value;
public Coin()
{
Throw();
}
public char Value
{
get { return value; }
}
public void Throw()
{
value = (rand.Next(2) == 0) ? 'H' : 'T';
}
public override string ToString()
{
return "" + value;
}
}
Explanation
You should represent a concept that here is a coin, and you can do that with a class, here named Coin. 
Note first that the class Coin has no Main() method and the methods are not declared static. A class is 
a concept \u2013 a type \u2013 which may be used in a program.
In C# a class contains four elements:
\u2022	 instance variables
\u2022	 constructors
\u2022	 properties
\u2022	 methods
and all four elements are present in the above class. The class has two variables:
private static Random rand = new Random();
private char value;
Download free eBooks at bookboon.com
Click on the ad to read more
C# 1 Introduction to programming and the C# language 
75 
Classes
The first is called rand and the type is Random. It has been declared static and is a bit special, so it 
is explained shortly. The second is called value and has the type char. It is the member variable that 
represents the coin. Note that both variables are declared private. This means that there is only access 
to these variables from the class\u2019s own methods \u2013 they can\u2019t be directly referenced from other classes 
that use the class Coin.
The class has a method called Throw(). When the method is performed, it simulate that the coin is 
thrown, thus giving it a new value:
value = (rand.Next(2) == 0) ? 'H' : 'T';
The method assigns the variable value a new random value. To that purpose it use the ? operator. It is 
an operator which has the form
condition ? expression1 : expression2;
and the meaning is that if the condition is true, the value is the value of expression1 and else the value 
of expression2.
\u201cThe perfect start 
of a successful, 
international career.\u201d
CLICK HERE 
to discover why both socially 
and academically the University 
of Groningen is one of the best 
places for a student to be www.rug.nl/feb/education
Excellent Economics and Business programmes at:
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
76 
Classes
Random is a class in the namespace System, and it has a method Next() that returns a random non 
negative integer. If you specify a parameter as Next(n), you gets a random value between 0 and n-1, 
both incl. Therefore
rand.Next(2)
is a random value 0 or 1, and equivalent thereto assigned to the member variable value a random 
character H and T.
The member variable value is private and can only be used inside the class Coin. The program, that 
should use the Coin class, has to know the value of a coin that is read the variable value. For that the 
class Coin has a property:
public char Value
{
get { return value; }
}
The property has the same type and same name as a member variable \u2013 just you write the name in 
uppercase. Note that a property is not syntactically a method (there are no parentheses after the name). 
The property has a get part that returns the value of the current member variable.
When creating an object of class Coin, the machine also creates an instance variable value. The coin can 
have only two legal values (H, T), and when the coin\u2019s value is the value of the variable value, the coin will 
have an illegal value until it is thrown. It\u2019s unfortunate, because that coins in the real world will always 
have a legal value, but also because a program that uses Coin class would fail. This problem is solved with 
a constructor. Syntactic is a method that does not have any type and which has the name of the class:
public Coin()
{
Throw();
}
A constructor is a method that is automatically executed when creating an object of a class, and it is 
typically used to initialize instance variables. In this case, the constructor throws the coin and thus 
ensures that a coin has a legal value once it is created. Note also that the only way a Coin can change its 
value is by throwing it. It is guaranteed by the member variable value is private.
When you have the class, you can create objects whose type is the Coin. You do it with the new operator, 
for example:
Coin c1 = new Coin();
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
77 
Classes
It creates an object named c1 whose type is Coin. When the new operator is performed, then the class\u2019s 
non-static member variables are created, and the class\u2019s constructor is automatically performed. The 
static member variables are created in a different way, and they are created only once. This means that 
static members are shared between all objects of the class. 
In this case the member variable rand is static and all objects of the class Coin will therefore apply the 
same rand variable. It is important, because otherwise all Coin objects initialize their own random number 
generator (which is initialized by reading the hardware clock) and the result would be that two objects 
created in the same place in the program would always have the same values.
In Main() the program creates two objects, called c1 and c2. After they are created the program goes 
into a do loop that throws the coins, and displays them on the screen. The loop runs until both coins 
show the value H. Notice how you throw a coin:
c1.Throw();
c1 is an object, and Throw() is a method in the class that defines the object. You execute the method on 
the current object using the dot operator. Note also how to refer to the coin\u2019s value:
c1.Value
Here you use the class\u2019s property, which returns the coin\u2019s value. Note that in this case, the class Coin 
has a property which is read only. Classes may also have properties that are read write, which will be 
apparent from other examples.
The class has also a method which is called ToString(), and which are not used in this example. Classes 
should generally have a ToString() method that returns a string that is a text representation of a concrete 
object. This means that an object can be printed with the method System.WriteLine(). Note that the 
method is defined as override. I will explained the meaning later.
Comment
A class has a type of visibility that is either public or internal. The class Coin has public visibility. This 
means that anyone can create objects of this type. Visibility can also be specified as