C Sharp
C Sharp
by
Willi-Hans Steeb
International School for Scientific Computing
[email protected]
Contents
1 Introduction 1
2 CSharp Basics 3
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Basic Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 Control Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.5 Logical Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.6 Pointers and References . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.7 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.8 Jump Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.9 Pass by Value, Pass by Reference . . . . . . . . . . . . . . . . . . . . 16
2.10 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.11 Bitwise Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.12 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3 Classes 22
3.1 Write your own class . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.2 Inheritence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.3 Overloading Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.4 Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.5 Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.6 Built-in classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.6.1 String Manipulations . . . . . . . . . . . . . . . . . . . . . . . 30
3.6.2 DateTime Class . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.6.3 ArrayList Class . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.6.4 Dictionary Class . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.6.5 Mathematics Class and Random Class . . . . . . . . . . . . . 34
3.6.6 Point Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
5 Graphics 47
6 Events 52
7 Threads 54
Bibliography 60
Index 60
ii
Preface
The book gives a collection of C# programs.
Without doubt, this book can be extended. If you have comments or suggestions,
we would be pleased to have them. The email addresses of the author are:
[email protected]
[email protected]
http://issc.rau.ac.za
iii
Chapter 1
Introduction
CSharp is designed for the .NET framework. The .NET framework is obeject ori-
ented. CSharp has a great set of tools for the object oriented programmer. CSahrp
is the first component oriented language in the C/C++ family. Component concepts
are first class:
Properties, methods, events
Design-time and run-time attributes
integrated documentation using XML
CSharp can be embedded in web pages. In C++ and Java primitive date types
(int, double, etc) are maginc and do not interoperate with objects. In Smalltalk
and Lisp primitive types are objects, but at great performence cost. CSharp unifies
this with no performance cost. CSharp also adds new primitive data types, for ex-
ample decimal. Collections work for all types.
initialize static fields for a type. We use the static keyword to indicate a type
constructor.
All types in the system are derived from class object. The class object contains
the functions string ToString() and bool Equals() which should be overriden
when we write our own class.
CSarp has built in support for events. This is useful for dealing with objects in an
event driven operating system. More than one type can register interest in a single
event. A single type can register interest in any number of events.
CSharp supports interfaces using the interface keyword. Our types can implement
interfaces. We must implement all methods. Interfaces can contain methods but no
fields with properties and events imcluded.
CSharp also provides type conversion, for example if char c = ’a’; we can convert
to int i = (int) c;.
Chapter 2
CSharp Basics
2.1 Introduction
Compile and link the programs with
csc filename.cs
Every Main method must be contained inside a class. In the first example this is
Hello1. The System.Console class contains a WriteLine() method that can be
used to display a string to the console. To avoid fully qualifying classes throughout
the program, we can use the using directive. Writing to the screen, where \n
provides a newline.
// cshello.cs
using System;
class Hello1
{
public static void Main()
{
Console.WriteLine("Hello Egoli\n");
Console.WriteLine("Good Night Egoli");
}
}
Writing to the screen using exception handling with try and catch block. To
access command line parameters we change the signature of the Main(void) to
Main(string[] args).
// hello2.csc
3
4 CHAPTER 2. CSHARP BASICS
using System;
class Hello2
{
public static void Main(string[] args)
{
try
{
Console.WriteLine("Hello {0}",args[0]);
}
catch(Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("Good Night");
} // end main
}
To read from the keyboard we use the method ReadLine(). The command Length
returns the number of elements in the array. Using if-else.
// hello3.csc
using System;
class Hello3
{
public static void Main(string[] args)
{
if(args.Length > 0)
{
Console.WriteLine("Hello {0}",args[0]);
}
else
{
Console.WriteLine("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hello {0}",name);
}
Console.WriteLine("Good Night");
} // end main
}
2.2. BASIC DATA TYPES 5
bool, byte, sbyte, char, short, ushort, int, unit, long, ulong
CSharp is a strongly typed language and therefore variables must be declared with
an available type and must be initialized with a value (or reference) of the same
type. Built-in types are also string and object.
// datatypes.cs
using System;
class Datatypes
{
public static void Main(string[] args)
{
bool b = true; // boolean data type
Console.WriteLine(!b); // logical NOT
long k = -234567899;
Console.WriteLine(k);
ulong l = 3456789123;
6 CHAPTER 2. CSHARP BASICS
Console.WriteLine(l);
++, --, +, -, *, /, %
Note that we have integer division and floating point division depending on the data
types.
// arithmetic.cs
using System;
class Arithmetic
{
public static void Main(string[] args)
{
byte c = 255;
c++;
Console.WriteLine(c);
sbyte d = -125; // signed byte
d--;
Console.WriteLine(d);
long m = -234567899;
long n = 345;
long p = m*n;
Console.WriteLine(p);
2.4. CONTROL STATEMENTS 7
int r1 = 27;
int r2 = 5;
int r3 = r1/r2;
Console.WriteLine("r3 = " + r3);
int r4 = r1%r2;
Console.WriteLine("r4 = " + r4);
double d1 = 3.14159;
double d2 = 4.5;
double d3 = d1/d2;
Console.WriteLine(d3);
using System;
class myIf
{
public static void Main(string[] args)
{
int i;
Console.WriteLine("Enter integer: ");
string line = Console.ReadLine();
i = System.Convert.ToInt32(line);
if(i > 5)
Console.WriteLine("The number is larger than 5");
8 CHAPTER 2. CSHARP BASICS
else
Console.WriteLine("The number is smaller than 5");
}
}
// forloop.cs
using System;
class forloop
{
public static void Main(string[] args)
{
double[] numbers = { 1.1, 2.2, 3.3, 4.4 };
int i = 0;
double sum = 0.0;
for(i=0;i<numbers.Length;i++)
{
sum += numbers[i];
}
Console.WriteLine("sum = {0}",sum);
for(i=0;i<x.Length;i++)
{
intsum += x[i];
}
Console.WriteLine(intsum);
} // end main
}
Another example for the for loop applied to numbers read from the keyboard.
// forloop1.cs
using System;
class ForLoop
{
public static int Main(String[] args)
2.4. CONTROL STATEMENTS 9
{
int sum = 0;
String line;
for(line=Console.In.ReadLine();line!="";line=Console.In.ReadLine())
{
sum += System.Convert.ToInt32(line);
}
Console.WriteLine(sum.ToString() + "\n");
return 0;
}
}
// foreachloop.cs
using System;
class foreachloop
{
public static void Main(string[] args)
{
string[] namelist = { "willi","otto","carl","john","otto" };
int count = 0;
string n = "otto";
// whileloop.cs
using System;
class whileloop
{
public static void Main(string[] args)
10 CHAPTER 2. CSHARP BASICS
{
int[] numbers = { 1, 2, 3, 4 };
int i = 0;
int sum = 0;
// dowhileloop.cs
using System;
class whileloop
{
public static void Main(string[] args)
{
double[] numbers = { 1.1, 2.3, 3.5, 4.5 };
int i = 0;
double sum = 0.0;
do
{
sum += numbers[i];
i++;
}
while(i < numbers.Length);
Console.WriteLine("sum = {0}",sum);
} // end main
}
// switch.cs
using System;
class Myswitch
{
2.5. LOGICAL OPERATIONS 11
// logical.cs
using System;
12 CHAPTER 2. CSHARP BASICS
class MyLogica
{
public static void Main()
{
int j;
Console.WriteLine(" Enter an integer: ");
string line = Console.ReadLine();
j = System.Convert.ToInt32(line);
Console.WriteLine();
int k;
Console.WriteLine("Enter an integer: ");
line = Console.ReadLine();
k = System.Convert.ToInt32(line);
Console.WriteLine();
int n;
Console.WriteLine("Enter an integer: ");
line = Console.ReadLine();
n = System.Convert.ToInt32(line);
if(n==0)
Console.WriteLine("The interger is zero");
else
Console.WriteLine("the integer is nonzero");
}
}
// pointers.cs
using System;
// references.cs
using System;
2.7 Recursion
Using recursion to find the Fibonacci numbers.
14 CHAPTER 2. CSHARP BASICS
// recursion.cs
using System;
class recur
{
public static ulong fib(ulong n)
{
if(n == 0) return 0;
if(n == 1) return 1;
return fib(n-1) + fib(n-2);
}
using System;
class Mygoto
{
public static void Main()
{
Random r= new Random(51);
L3:
int a = r.Next(100);
int b = r.Next(100);
int result;
L1:
Console.WriteLine("{0} + {1} =",a,b);
string s = Console.ReadLine();
result = Convert.ToInt32(s);
if(result == (a+b))
goto L2;
Console.WriteLine("sorry you are not correct: try again");
2.8. JUMP STATEMENTS 15
goto L1;
L2:
Console.WriteLine("congratulations you are correct");
Console.WriteLine("Want to add again: Press y for yes and n for no: ");
string t = Console.ReadLine();
if(t == "y") goto L3;
if(t == "n")
{
Console.WriteLine("bye, see you next time around");
goto L4;
}
L4:
int e = 0;
}
}
Using Exit()
// password.cs
using System;
class password
{
public static void Main()
{
string password = "XYA";
int i,j,k;
for(i=65;i<91;i++)
{
for(j=65;j<91;j++)
{
for(k=65;k<91;k++)
{
char c1 = (char) i;
char c2 = (char) j;
char c3 = (char) k;
char[] data = { c1,c2,c3 };
string s = new string(data);
bool found = password.Equals(s);
if(found == true)
{
Console.WriteLine("Password = {0}",s);
Environment.Exit(0);
16 CHAPTER 2. CSHARP BASICS
}
}
}
}
}
}
// passing.cs
using System;
// Divide.cs
using System;
class Divider
{
public static int Divide1(int dividend,int divisor,out int r)
{
int quot = dividend/divisor;
r = dividend - quot*divisor;
2.10. ARRAYS 17
return quot;
}
int s;
int t;
Divide2(145,3,out s,out t);
Console.WriteLine("Quotient = {0} and Remainder = {1}",s,t);
}
}
2.10 Arrays
C# supporst one-dimensional arrays, multidimensional arrays (rectangular arrays)
and arrays of arrays (jagged arrays). As C, C++ and Java C# arrays are zero
indexed. This means the array indexes start as zero. When declaring arrays,
the square bracket [] must come after the type, not the identifiers, for example
int[] table. The size of the array is not part of its type as it is in the C language.
Thus
In C# arrays are actually objects. System.Array is the abstract base type of all
array types.
// myArray.cs
using System;
class myArray
{
public static void Main()
{
int[] numbers = { 4, 12345, 890, 23456789 };
18 CHAPTER 2. CSHARP BASICS
Array.Sort(slist);
Console.Write("pos2 = {0}",pos2);
Console.WriteLine();
// twodim.cs
using System;
matrix[0][0] = 2; matrix[0][0] = 4;
matrix[1][0] = 7; matrix[1][1] = 3;
int i = 1;
Console.WriteLine("matrix[" + i + "][" + i + "] = " + matrix[i][i]);
double[,] myarray;
myarray = new double[2,3];
myarray[0,0] = 3.1;
myarray[0,1] = 4.7;
myarray[0,2] = 3.3;
myarray[1,0] = 2.7;
myarray[1,1] = 1.1;
myarray[1,2] = 7.3;
double r = myarray[0,1]*myarray[1,2];
Console.WriteLine("r = " + r);
}
}
& AND
| OR (inclusive OR)
^ XOR (exclusive OR)
~ NOT
// bitwise.cs
using System;
class MylBitwise
{
public static void Main()
{
int r3 = 4; int r4 = 5;
int r5 = r3 & r4; // bitwise AND
Console.WriteLine("Binary AND of 4 and 5 gives {0}",r5);
int x = 125;
int r10 = x^x;
Console.WriteLine("Binary XOR of 125 with itself gives {0}",r10);
int r12 = 4;
int r13 = ~r12; // one’s complement
int r14 = ++r13;
Console.WriteLine("two’s complement of 4 {0}",r14);
}
}
2.12 Types
The typeof command
// myTypeof.cs
using System;
using System.Text;
class myTypeof
{
public static void Main()
{
double b = 3.14;
string s = "xxx";
StringBuilder sb = new StringBuilder("123456789");
Type at = typeof(double);
Console.WriteLine("at = {0}",at);
Type st = typeof(string);
Console.WriteLine("st = {0}",st);
Type sbt = typeof(StringBuilder);
Console.WriteLine("sbt = {0}",sbt);
}
}
Chapter 3
Classes
// Person1.cs
using System;
class Person1
{
private string myName = "N/A";
private int myAge = 0;
private char mySex = ’n’;
class Person1 defines three private member variables, myName, myAge, mySex.
These variable are visible only inside the body of class Person1. To access these
variable outside the class we use the special property methods Name, Age, and Sex.
The CSharp compiler translates for example the Name property to a pair of methods,
namely
The class Person1 contains the Main() method. In some application it would be
better to keep the class Person1 without the Main() method and have an extra
file which calls the Person objects. Generate dll for file Person.cs.
// Person.cs
using System;
24 CHAPTER 3. CLASSES
// PersonMain.cs
using System;
class permain
{
public static void Main()
{
Console.WriteLine("Simple Properties");
3.2. INHERITENCE 25
person2.Name = "Koos";
person2.Age = 27;
person2.sex = ’M’;
3.2 Inheritence
In the next program we use inheritence. The class Car is derived from class Vehicle.
// MVehicle.cs
using System;
class Vehicle
{
private int weight;
private int topSpeed;
private double price;
public Vehicle() {}
price = aPrice;
}
public Car() { }
class myCar
{
public static void Main()
{
Vehicle aVehicle = new Vehicle(15000,120,30000.00);
Console.Write("A vehicle: ");
aVehicle.print();
Console.WriteLine("");
Car aCar = new Car(3500,100,12000.00,6,120,300);
Console.Write("A car: ");
aCar.print();
Console.WriteLine("");
}
}
using System;
using System;
class ComplexMain
{
public static void Main()
{
Complex r1 = new Complex(1.0,2.0);
Complex r2 = new Complex(2.0,1.0);
r1 = r1 + r2;
Console.WriteLine("Answer is Real: {0} Imaginary: {1}i",r1.real,r1.imaginary);
}
}
3.5 Structures
In CSharp we can also use structures. The program also shows how enumeration
can be used.
// enumeration.cs
using System;
struct ClubMember
{
public string Name;
public int Age;
public MemberType Group;
}
class enumeration
{
public static void Main(string[] args)
{
ClubMember a; // Value types are automatically initialized
a.Name = "John";
a.Age = 13;
a.Group = MemberType.Eagles;
using System;
using System.Text;
class mystring
{
public static void Main(string[] args)
{
string s1 = "otto";
int length = s1.Length;
Console.WriteLine(s1); // => otto
Console.WriteLine(length); // => 4
string s2 = "willi";
s2 = s2.Replace(’l’,’t’);
Console.WriteLine(s2); // witti
string s3 = "Johannesburg";
string result = s3.Substring(3,5);
Console.WriteLine(result); // => annes
string s4 = "olli&ulli&ruedi";
string[] textarray = s4.Split(’&’);
Console.WriteLine(textarray[1]); // => ulli
string s7 = string.Join(":",textarray);
Console.WriteLine(s7); // => olli:ulli:ruedi
} // end main
}
using System.Text;
// mystringbuilder.cs
using System;
using System.Text;
class mystringbuilder
{
public static void Main(string[] args)
{
string s8 = "carl";
StringBuilder b1 = new StringBuilder(s8.Length+5);
b1.Append("carl");
b1.Append("-uli");
Console.WriteLine(b1); // carl-uli
// thuemorse.cs
using System.Text;
using System;
class TueMorse
{
public static void Main()
{
32 CHAPTER 3. CLASSES
// myDate.cs
using System;
class myDate
{
public static void Main()
{
DateTime dt = DateTime.Now;
// arraylist.cs
using System;
using System.Collections;
class arraylist
3.6. BUILT-IN CLASSES 33
{
public static void Main(string[] arg)
{
ArrayList alist = new ArrayList();
foreach(string s in arg) alist.Add(s);
for(int i=0;i<alist.Count;i++)
{
Console.Write("{0}",alist[i]);
}
Console.Write("\n");
string s1 = "Xena";
Console.Write("Argument Count:{0}\n",alist.Count);
alist.Insert(3,s1);
alist.RemoveAt(1);
using System;
using System.Collections;
using System.Collections.Specialized;
class Dictionary
{
public static void Main()
{
ListDictionary population = new ListDictionary();
population.Add("Johannesburg",9345120);
population.Add("CapeTown",3500500);
population.Add("Durban",550500);
Console.WriteLine("{0} = {1}",name.Key,name.Value);
}
} // end Main()
}
// distance.cs
using System;
class Distance
{
public static void Main()
{
double r = 6371.0;
double alpha1, alpha2, beta1, beta2, temp, theta, distance;
char dir;
string source, dest, line;
line = Console.ReadLine();
temp = (double) System.Convert.ToInt32(line);
alpha1 += temp/60.0;
Console.WriteLine("W/E: ");
line = Console.ReadLine();
dir = line[0];
if(dir == ’E’ || dir == ’e’) alpha1 = -alpha1;
alpha1 *= Math.PI/180.0;
alpha2 *= Math.PI/180.0;
beta1 *= Math.PI/180.0;
beta2 *= Math.PI/180.0;
temp = Math.Cos(beta1)*Math.Cos(beta2)*Math.Cos(alpha1-alpha2)
+ Math.Sin(beta1)*Math.Sin(beta2);
theta = Math.Acos(temp);
distance = r*theta;
Console.WriteLine("The distance between {0} and {1} is {2} km",
36 CHAPTER 3. CLASSES
source,dest,distance);
}
}
// random.cs
using System;
class LearnRandom
{
public static void Main()
{
Random r = new Random();
Console.WriteLine("Random sequence(no seed,limit 0..int.MaxVal)");
Console.WriteLine();
for(int i=0;i<10;i++)
Console.WriteLine("random no: {0}",r.Next());
Console.WriteLine("Random sequence(no seed,limit 0..10)");
for(int i = 0;i<10;i++)
Console.WriteLine("random no: {0}",r.Next(10));
Console.WriteLine("Random sequence(no seed,limit 50..100)");
for(int i=0;i<10;i++)
Console.WriteLine("random no: {0}",r.Next(50,100));
Console.WriteLine("Random sequence(no seed, limit 0..1)");
for(int i=0;i<10;i++)
Console.WriteLine("random no: {0}",r.NextDouble());
Console.WriteLine("Random sequence in byte array(no seed,limit 0..1)");
byte[] b = new byte[5];
r.NextBytes(b);
for(int i=0;i<b.Length;i++)
Console.WriteLine("random byte: {0}",b[i]);
}
}
using System;
using System.Windows.Forms;
using System.Drawing;
class PointTest
3.6. BUILT-IN CLASSES 37
{
public static void Main()
{
Point p = new Point(23,13);
Console.WriteLine("Our Point is: " + p);
int xcoord = p.X;
int ycoord = p.Y;
Console.WriteLine("The x coordinate is " + xcoord);
Console.WriteLine("The y coordinate is " + ycoord);
Point q = new Point(xcoord, ycoord);
bool b = p.Equals(q);
Console.WriteLine(" the points are equal: " + b);
4.1 Introduction
A stream is a sequence of bytes. The Stream class and its subclasses provide a
generic view of data sources and repositories, isolating the programmer from the
specific details of the operating system and underlying devices. Streams involve the
following three operations:
1) Streams can be read from. Reading is the transfer of data from a stream into a
data structure, such as an array of bytes.
2) Streams can be written to. Writing is the transfer of data from a data structure
into a stream.
3) Streams can support seeking. Seeking is the query and modifying of the current
position within a stream.
// BinaryIO.cs
using System;
using System.IO;
using System.Text;
class BinaryIO
{
private static void WriteData(int i,double d,string t,char c,StringBuilder sb)
{
Stream s = File.OpenWrite("info.dat");
BinaryWriter bw = new BinaryWriter(s);
38
4.3. TEXT FILE MANIPULATION 39
bw.Write(i);
bw.Write(d);
// write length-prefixed string
bw.Write(t);
bw.Write(c);
bw.Write(sb.ToString());
bw.Close();
}
WriteData(12345,3.14159,"Hello Egoli",’y’,sb);
ReadData();
}
}
using System;
using System.IO;
using System.Text; // for encoding
class ReadFile
{
public static void Main(string[] args)
40 CHAPTER 4. STREAMS AND FILE MANIPULATIONS
{
Stream s = new FileStream(args[0],FileMode.Open);
int size = (int) s.Length;
byte[] buffer = new byte[size];
s.Read(buffer,0,buffer.Length);
s.Close();
string text = Encoding.ASCII.GetString(buffer);
Console.WriteLine(text);
}
}
// writefile.cs
using System;
using System.IO;
using System.Text; // for encoding
class WriteFile
{
public static void Main(string[] args)
{
Stream s = new FileStream(args[1],FileMode.Append,FileAccess.Write);
string text = args[0] + "\r\n"; // append end of line characters
byte[] buffer = Encoding.ASCII.GetBytes(text);
s.Write(buffer,0,buffer.Length);
s.Close(); // also flushes the stream
}
}
// placeorder.cs
using System;
using System.IO;
class PlaceOrder
{
public static void Main(string[] args)
{
DateTime dt = DateTime.Now;
string today = dt.ToString("dd-MMM-yyyy");
string record = today + "|" + String.Join("|",args);
StreamWriter sw = new StreamWriter("order.txt",true);
4.4. BYTE BY BYTE MANIPULATION 41
sw.WriteLine(record);
sw.Close();
}
}
// BytebyByte.cs
using System;
using System.IO;
In the following example we copy byte by byte a file into another file.
// TestFile.cs
using System;
using System.IO;
class TestFile
{
static void Copy(string from,string to,int pos)
{
try
{
FileStream sin = new FileStream(from,FileMode.Open);
FileStream sout = new FileStream(to,FileMode.Create);
sin.Seek(pos,SeekOrigin.Begin);
int ch = sin.ReadByte();
42 CHAPTER 4. STREAMS AND FILE MANIPULATIONS
while(ch >=0)
{
sout.WriteByte((byte)ch);
ch = sin.ReadByte();
}
sin.Close();
sout.Close();
}
catch (FileNotFoundException e)
{
Console.WriteLine("--file {0} not found",e.FileName);
}
}
// Oops1.cs
using System;
using System.IO;
class Oops
{
public static void Main()
{
char cl = ’{’;
int countcl = 0;
char cr = ’}’;
int countcr = 0;
}
fin.Close();
Console.WriteLine("countcl = " + countcl);
Console.WriteLine("countcr = " + countcr);
}
}
using System;
using System.Runtime.Serialization;
[Serializable]
public class Employee
{
public string Name;
public string Job;
public double Salary;
public Employee() { }
// binsertest1.cs
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
class BinarySerializatioTest1
{
static BinaryFormatter bf = new BinaryFormatter();
</employee>
<employee id="102">
<name> Jane </name>
<job> steno </job>
<salary> 23000 </salary>
</employee>
<employee id="103">
<name> Jim </name>
<job> salesman </job>
<salary> 36000 </salary>
</employee>
<employee id="104">
<name> Jill </name>
<job> clerk </job>
<salary> 45000 </salary>
</employee>
<employee id="105">
<name>Jeff</name>
<job>CEO</job>
<salary>105000</salary>
</employee>
</employees>
The program listemp.cs displays id, and salary of each employee in the file
emp.xml.
// listemp.cs
using System;
using System.Xml;
class ListEmployees
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
// load employee.xml in XmlDocument
doc.Load("emp.xml");
// obtain a list of all employee element
XmlNodeList list = doc.GetElementsByTagName("employee");
foreach(XmlNode emp in list)
{
// obtain value of id attribute of the employee tag
string id = emp.Attributes["id"].Value;
46 CHAPTER 4. STREAMS AND FILE MANIPULATIONS
The program addemp.cs takes inforations from the command line (id, name, job,
salary) and makes a new entry in the file emp.xml.
// addemp.cs
using System;
using System.Xml;
class AddEmployee
{
public static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load("emp.xml");
// create a new employee element and value of its attribute
XmlElement emp = doc.CreateElement("employee");
emp.SetAttribute("id",args[0]);
// create a name tag and st its value
XmlNode name = doc.CreateNode("element","name","");
name.InnerText = args[1];
// make name tag a subtag of newly created employee tag
emp.AppendChild(name);
XmlNode job = doc.CreateNode("element","job","");
job.InnerText = args[2];
emp.AppendChild(job);
XmlNode sal = doc.CreateNode("element","salary","");
sal.InnerText = args[3];
emp.AppendChild(sal);
// add the newly created employee tag to the root (employees) tag
doc.DocumentElement.AppendChild(emp);
// save the modified document
doc.Save("emp.xml");
}
}
Graphics
The Graphics object provides methods for drawing a variety of lines and shapes.
Simple or complex shapes can be rendered in solid or transparent colors, or using
user-defined gradient or image textures. Lines, open curves, and outline shapes are
created using a Pen object. To fill in an area, such as a rectangle or a closed curve,
a Brush object is required.
// HelloGraphics.cs
using System;
using System.Drawing;
using System.Windows.Forms;
g.DrawRectangle(new Pen(Color.Pink,3),20,20,150,100);
}
The method DrawString() takes four arguments as shown in the above example.
Every method in the Graphics class has to be accessed by creating an object of that
class. We can easily update the above program to render other graphical shapes like
Rectangle, Ellipse, etc. All we have to do is to apply the relevant methods ap-
propriately.
Using the Pen class we can specify colour of the border and also the thichmess. The
Pen class is applied for drawing shapes while Brush is applied for filling shapes.
// draw.cs
using System;
using System.Drawing;
using System.Windows.Forms;
// Winhello.cs
using System;
using System.Windows.Forms;
49
using System.ComponentModel;
using System.Drawing;
public WinHello()
{
Text = "Hello World";
Size = new Size(400,400);
bnclick = new Button();
bnclick.Text = "Click.Me";
bnclick.Size = new Size(60,24);
bnclick.Location = new Point(20,60);
bnclick.Click += new EventHandler(bnclick_Click);
Controls.Add(bnclick);
Closing += new CancelEventHandler(WinHello_Closing);
}
Next we provide that display images. The file formats could be bmp, gif or jpeg.
// mydrawim.cs
50 CHAPTER 5. GRAPHICS
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
// textbru.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public Texturedbru()
{
this.Text = "Using Texture Brushes";
Image bgimage = new Bitmap("forest.bmp");
bgbrush = new TextureBrush(bgimage);
this.Paint += new PaintEventHandler(Text_bru);
51
Events
// evthand.cs
using System;
using System.Windows.Forms;
using System.Drawing;
52
53
Threads
A process in its simplest form is a running application. The Process class provides
access to local and remote processes and enables us to start and stop local system
processes.
A thread is an execution stream within a process. A thread is also called a lightweight
process. It has it own execution stack, local variables, and program counter. There
may be more than one thread in a process. The Process.Start() method starts
a process resource by specifying the name of a document or application file and
associates the resource with a new process component. Thus we can start other
applications from within our application.
// process2.cs
using System;
using System.Diagnostics;
class ProcessTest
{
public static void Main()
{
Process p = Process.Start("notepad.exe");
Process w = Process.Start("winhlp.exe");
Process p = Process.Start("notepad.exe","c:\\csharp\\process2.cs");
54
55
\begin{verbatim}
// threadtest1.cs
using System;
using System.Threading; // for Thread class
class ThreadTest1
{
public static void SayHello()
{
for(int i=1;;i++)
{
Console.WriteLine("Hello {0}",i);
}
}
// threadtest2.cs
using System;
using System.Threading; // for Thread class
class ThreadTest2
{
public static void SayHello()
{
for(int i=1;;i++)
{
Console.WriteLine("Hello {0}",i);
}
56 CHAPTER 7. THREADS
// sleepingthread.cs
using System;
using System.Threading;
class SleepingThread
{
public static void Run()
{
for(int i=1;i<6;i++)
Console.WriteLine("Welcome {0}",i);
try
{
Thread.Sleep(5000);
}
catch(ThreadInterruptedException e)
{
Console.WriteLine("Sleep Interrupted");
}
Console.WriteLine("Goodbye");
}
// joiningthread.cs
using System;
using System.Threading;
class JoiningThread
{
public static void Run()
{
for(int i=1; i<16; i++)
Console.WriteLine("Hello {0}",i);
}
// waitingthread.cs
using System;
using System.Threading;
class WaitingThread
{
static object obj = new object();
{
new Thread(new ThreadStart(Run)).Start();
for(int i=1; i<16; i++)
Console.WriteLine("Hello : {0}",i);
Monitor.Enter(obj);
Monitor.Wait(obj);
Monitor.Exit(obj);
Console.WriteLine("Goodbye");
}
}
// syncthreads1.cs
using System;
using System.Threading;
class Account
{
private double balance = 5000;
class SymnThread
{
static Account acc = new Account();
// syncthreads2.cs
using System;
using System.Threading;
class Account
{
private double balance = 5000;
class SymnThread
{
static Account acc = new Account();
[1] Horton Ivor, Beginning Java 2, WROX Press, Birmingham, UK, 1999
[2] Jaworski Jamie, Java 1.2 Unleashed, SAMS NET, Macmillan Computer Pub-
lishing, USA, 1998
[5] Willi-Hans Steeb, The Nonlinear Workbook: Chaos, Fractals, Cellular Au-
tomata, Neural Networks, Genetic Algorithms, Fuzzy Logic with C++, Java,
SymbolicC++ and Reduce Programs, World Scientific, Singapore, 1999
[6] Tan Kiat Shi, Willi-Hans Steeb and Yorick Hardy, SymbolicC++: An Intro-
duction to Computer Algebra Using Object-Oriented Programming, 2nd edition
Springer-Verlag, London, 2000
60
Index
Enumeration, 29
Event, 52
Inheritence, 25
Jagged arrays, 17
Operator overloading, 28
Process, 54
Sealed, 34
Structures, 29
Thread, 54
61