Learn C#
Learn C#
Learn C#
The do-it-yourself
yourself way
Get the
gist of the
concept
Write
the
program
Quasar S. Chunawalla
1|Page
Learn C# - do it yourself way... 2008
2|Page
Learn C# - do it yourself way... 2008
Program Listing
3|Page
Learn C# - do it yourself way... 2008
4|Page
1
Introduction to C#
1|Page
Learn C# - do it yourself way... 2008
using System;
class Greeting
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World");
}
}
The program starts with the using statement. Wait for a while, till I
tell you what it means. Then, we declare a class called Greeting. All
code in C# must be written inside a class.
Next, we have written Main(). The word Main() indicates this is the
start of the program. This is where the C# system start the
executing(running) the program. Thus, Main() is the entry
point(starting point) of any program. All statements written inside
Main() are executed line by line. The Main() block is started using a
starting curly brace { and terminated using an ending curly brace }.
Whatever you want to write inside Main() must be enclosed within
this pair of curly braces. On the same lines, whatever you write inside
the class, must be enclosed within { ... }.
2|Page
Learn C# - do it yourself way... 2008
So, what really are objects. Any real world entity or thing, say for
example a car, a person, a flight, a ticket-booking, an employee, a
college can be an object in C#. To model real world things, in C# we
create objects.
Just like in the real – world, each object has some features or
characteristics that describe the object, our C# objects also have
features that describe the object. For example, every car has some
name, brand, year of manufacture, price, color which describe it. In
C#, to model this concept, C# car object will also have attributes
name, brand, yearOfManufacture, price, color etc. Every car object
will have its own values of these attributes. Consider the following
two car objects –
3|Page
Learn C# - do it yourself way... 2008
Before you get to know, how this is done, let’s take brief look at how
Computer memory looks. Just like
like in a street, people live in houses,
computer memory is organised as a series of cells. The cells do not
house people, instead they house data. We can visualise the picture of
computer memory likee the one below :
5|Page
Learn C# - do it yourself way... 2008
6
Polymorphism, Constructors
and Destructors
class OverloadDemo
{
public static void Main()
{
Test t = new Test();
6|Page
Learn C# - do it yourself way... 2008
7|Page
Learn C# - do it yourself way... 2008
This time round, the Multiply() method can multiply one int with one
double value, and returns a double result as the answer. Thus, we are
again assigning a new extra meaning to the Multiply() method. So,
once again we have overloaded the Multiply() function.
This new version of the Multiply() method can now multiply a double
with an integer. Mutiplying a double with an int, is different from
multiplying an int with a double.
8|Page
Learn C# - do it yourself way... 2008
1. When two or more methods in the same class have the same name
2. They have different Parameter Lists
{
bool ans;
int days1 = d1.day + d1.month * 30 + d1.year * 365;
int days2 = d2.day + d2.month * 30 + d2.year * 365;
class DateDemo
{
public static void Main()
{
Date d1 = new Date();
Date
Date d2 = new Date();
Date
Date result;
bool ans;
d1.day = 2;
d1.month = 7;
d1.year = 5;
d2.day = 29;
d2.month = 6;
d2.year = 4;
result = d1 + d2;
d1.GetDate();
d2.GetDate();
result.GetDate();
10 | P a g e
Learn C# - do it yourself way... 2008
When the C# system encounters this line, it does not directly add the
2 + 3. Instead, the C# system calls a function with the name + and
passes 2 and 3 as the arguments.
+(2,3)
When this function is called, the control jumps to the function
definition. The + function looks like this
But, since these our own objects, we have created them, we have
made their class design, the + operator does not know how to add
these custom made objects. To be able to add them, we need to define
the following function -
11 | P a g e
Learn C# - do it yourself way... 2008
return result;
}
12 | P a g e
Learn C# - do it yourself way... 2008
return ans;
}
6.3 Constructors
class Box
{
double width;
double height;
double depth;
public Box()
{
width = height = depth = 1;
}
public Box(int l)
{
width = height = depth = l;
}
13 | P a g e
Learn C# - do it yourself way... 2008
class BoxDemo
{
public static void Main()
{
Box myBox1 = new Box();
Box myBox2 = new Box(5);
Box myBox3 = new Box(10, 20, 30);
myBox1.GetBox();
myBox2.GetBox();
myBox3.GetBox();
;
myBox1.Volume();
myBox2.Volume();
myBox3.Volume();
}
}
Why Constructors?
When we first create an object, all its fields are initialised
initialised to 0. In
other words, the memory is zeroed out.
Box myBox;
myBox = new Box();
14 | P a g e
Learn C# - do it yourself way... 2008
myBox.width = 10;
myBox.height = 20;
myBox.depth = 30;
Well, you can use convenience methods like SetBox(). But, when you
have a thousand objects, you have explicitly call/invoke SetBox()
method on each Box object. Once again, it calls for a lot of work.
15 | P a g e
Learn C# - do it yourself way... 2008
Q. But, the classes that we have written till now seemed to work fine
without a constructor.
A. If you do not write your own constructor, the C# Compiler adds a
constructor method for you for free. Such a constructor is called the
default constructor.
Q. But how does the default constructor know, what I want it to do?
A. It does not! That’s why, it does not accept any parameters and has
empty body. It looks like this –
public Box()
{
}
Thus, the free constructor that C# compiler adds for you, is a do-
nothing constructor.
16 | P a g e
Learn C# - do it yourself way... 2008
In C#, you can have two kinds of resources in the programs you write.
The Objects of a class, primitive data-types etc. are supported by C#,
and the space occupied by them is automatically release by the GC,
when it finds they are no longer in use. Such resources are called
Managed Resources.
If you write a destructor in the class, it is called just before the objects
of this class are destroyed by GC. There are two ways to write a
destructor –
class MyClass
{
~MyClass()
{
Console.WriteLine("You can free up an unmanaged resources here.");
}
}
17 | P a g e
Learn C# - do it yourself way... 2008
class DestroyDemo
{
public static void Main()
{
MyClass obj = new MyClass();
obj = null;
}
}
A destructor has the same name as the class, but prefixed with a ~
tilde sign. Internally, this Destructor is translated to a call to the
Finalize() method –
class MyClass
{
protected override void Finalize()
{
try
{
Console.WriteLine("You can free up any unmanaged resources
here");
}
finally
{
base.Finalize();
}
}
}
Now, when you have a number of objects, the order in which these
objects will be destroyed/finalized is not fixed or known. Say, if we
have five objects obj1, obj2, obj3, obj4, obj5 of a class MyClass. The
GC may decide to destroy the objects in any random order say, for
example obj3, obj5,obj1, obj4, obj2. The GC maintains a queue of all
the objects that are to be finalized. This is called Finalization Queue.
18 | P a g e
Learn C# - do it yourself way... 2008
7
Inheritance – Our objects’
family tree
19 | P a g e
Learn C# - do it yourself way... 2008
domain, she finds out that there are Employees which are paid on an
hourly basis, or employees which are on contract basis.
The first mistake Kathy made was to add a field of type salary to
Employee. She discovers although employees are the objects in our
problem domain, there are actually two different types of Employee
objects : Salaried Employees and Hourly Employees. Therefore, we
should write two classes : Salary and Hourly.
class Hourly
{
public string name;
public string address;
public int SSN;
public int number;
public int hoursWorked;
public int hourlyRate;
Although Salary and Hourly classes are different types, they are not
entirely different. In fact, the two types of employees have a lot in
common, as seen by the repetition of fields and methods in these two
20 | P a g e
Learn C# - do it yourself way... 2008
classes. So, we can take the common elements from both the classes,
and put them in a parent class leaving the unique elements behind in
the child class. We can simply make the Salary and Hourly classes
inherit the elements of the Employee class.
If you want to make Salary and Hourly the child classes of Employee,
we write them as follows :
class Employee
{
public string name;
public string address;
public int SSN;
public int number;
}
When your classes use inheritance, you only need to write your code once.
In the above scenario, Salary class and the Hourly class have a lot of
same code.
21 | P a g e
Learn C# - do it yourself way... 2008
When you have two classes which are more specific cases of
something more general, you can set them up to inherit from the same
base class.
Employee
name
address
SSN
number
GetEmployee()
Salary Hourly
salary hourlyRate
hoursWorked
computePay()
computePay()
Build up your class model, by starting General and getting more Specific
22 | P a g e
Learn C# - do it yourself way... 2008
class EmployeeDemo
{
public static void Main()
{
Employee e = new Employee();
e.name = "Robert Smith";
e.address = "111 Palm street";
e.SSN = 999901111;
e.number = 1;
23 | P a g e
Learn C# - do it yourself way... 2008
e.GetEmployee();
s.GetEmployee();
h.GetEmployee();
}
}
class Employee
{
public string name;
public string address;
public int SSN;
public int number;
24 | P a g e
Learn C# - do it yourself way... 2008
class EmployeeDemo
{
public static void Main()
{
Employee e = new Employee();
e.name = "Robert Smith";
e.address = "111 Palm street";
e.SSN = 999901111;
e.number = 1;
e.GetEmployee();
s.GetEmployee();
h.GetEmployee();
}
}
25 | P a g e
Learn C# - do it yourself way... 2008
public Employee()
{
Console.WriteLine("Inside Grandparent");
}
public Salary()
{
Console.WriteLine("Inside Parent");
}
class EmployeeDemo
{
public static void Main()
{
PartTimeSalary pts = new PartTimeSalary();
}
}
using System;
27 | P a g e
Learn C# - do it yourself way... 2008
8
Advanced C# Language
Concepts
8.1 Using Parent class references to
Child Objects
An object reference can refer to an object of its class, or to an object
of any class derived from it by Inheritance. Suppose, we have the
following class hierarchy.
For example, if Animal class is the parent, and Bird is its child,
SongBird is the child of Bird and so on,... Animal reference can refer
to a Bird object or a SongBird object.
Animal a;
28 | P a g e
Learn C# - do it yourself way... 2008
a = new Animal();
a = new Bird();
a = new SongBird();
It is the type of object being reference, not the reference type, which
determines which method is invoked. Polymorphic references are
therefore resolved at run-time, not during compilation; hence it is
called dynamic binding.
class Shape
{
public virtual void Area()
{
}
}
29 | P a g e
Learn C# - do it yourself way... 2008
30 | P a g e
Learn C# - do it yourself way... 2008
class ShapeDemo
{
public static void Main()
{
int choice;
Shape s = new Shape();
while (true)
{
Console.WriteLine("Enter a choice : ");
Console.WriteLine("1 - Rectangle");
Console.WriteLine("2 - Triangle");
Console.WriteLine("3 - Cube");
Console.WriteLine("4 - Box");
Console.WriteLine("5 - Exit");
choice = Convert.ToInt32(Console.ReadLine());
if (choice == 1)
s = r;
if (choice == 2)
s = t;
if (choice == 3)
s = c;
if (choice == 4)
s = b;
if (choice == 5)
break;
31 | P a g e
Learn C# - do it yourself way... 2008
An abstract class might initially seem like an odd design. Why write a
class and not allow anyone to create objects of it?
We can make it, so that no one can create objects of Employee class,
by declaring the Employee class abstract. The only result of making
the Employee class abstract is that we can no longer create objects of
Employee.
Employee e;
e = new Employee(“George W.”,”Houston”,43); //Error
Just like you can make a class abstract, you can also make a method
abstract. For example, we could have a computePay() method in the
Employee class as abstract.
32 | P a g e
Learn C# - do it yourself way... 2008
8.5 Namespaces
Every class belongs to a namespace. Namespaces basically have two
purposes –
1. Namespace provides a mechanism for organising classes.
2. Namespace does compartmentalization.
33 | P a g e
Learn C# - do it yourself way... 2008
perform basic Input and Output are in System namespace. The classes
used for GUI applications are in System.Windows.Forms namespace.
The classes used for creating threads are in System.Threading
namespace.
Q. I have seen this problem before. Why don’t you change the names
of the classes, such as Vehicle1 and Vehicle2?
No thanks. I would have to re-write and re-compile a bunch of code.
With namespaces, I don’t have to worry about it. If the two Vehicle
classes are in different namespace/compartments, my C# program can
distinguish between the two Vehicle classes.
namespace A{
...
}
34 | P a g e
Learn C# - do it yourself way... 2008
using System;
namespace payroll
{
public class Employee
{
//Body of the class
}
The Employee, Salary and Hourly classes are now all in the same
namespace.
Suppose you have a written a Vehicle class, and I too have written a
Vehicle class. Kate wants to use both the Vehicle classes in their
program. So, I put my Vehicle class in a compartment quasar, and you
put your vehicle class in another compartment student. Kate will now
refer to both the Vehicle classes as,
35 | P a g e
Learn C# - do it yourself way... 2008
quasar.Vehicle
student.Vehicle
To create objects of these classes, Kate would write
Thus, from the above example, you can deduce the fact that,
namespaces help you to avoid naming conflicts by creating
compartments.
namespace payroll
{
public class Employee
{
public string name;
public string address;
public int SSN;
public int number;
36 | P a g e
Learn C# - do it yourself way... 2008
class Boss
{
public static void Main()
{
payroll.Employee e = new payroll.Employee("Jane Smith", "111 Oak
drive", 999001111, 1);
}
}
class Boss
{
public static void Main()
{
Employee e = new Employee("Jane Smith", "111 Oak street",
999001111, 1);
}
}
37 | P a g e
Learn C# - do it yourself way... 2008
Assembly
MyProgram.exe
8.10 Interfaces
An interface is a collection of abstract members. A class implements
an interface thereby inheriting the abstract methods of the interface.
All the methods of an interface need to be defined in the class.
38 | P a g e
Learn C# - do it yourself way... 2008
39 | P a g e
Learn C# - do it yourself way... 2008
40 | P a g e
Learn C# - do it yourself way... 2008
interface MyInterface
{
void a();
void b();
}
void b(){
Console.WriteLine(“Inside B”);
}
void c(){
Console.WriteLine(“Inside C”);
}
}
Using iref, we can call the methods a() and b(), but we cannot call the
method c(). Thus, we can call only those methods on the object,
which are declared and exposed by the interface.
41 | P a g e
Learn C# - do it yourself way... 2008
42 | P a g e
Learn C# - do it yourself way... 2008
payroll.PayEmployee(e);
hr.GetInfo(e);
hr.ChangeName(e, "Bill Gates");
hr.UpdateAddress(e, "Redmond VA");
}
}
43 | P a g e
Learn C# - do it yourself way... 2008
9
File Reading and Writing – I/O
44 | P a g e
Learn C# - do it yourself way... 2008
enum FileMode{
CreateNew,
Create,
Open,
OpenOrCreate,
Truncate,
Append
}
Create always creates a new file. CreateNew create a new new file, and if
the file already exists, it overwrites the old file. OpenOrCreate works
in 2 ways – if the file does not exist, it creates the file, if the file exists
45 | P a g e
Learn C# - do it yourself way... 2008
it will open the file. Open simply opens the file. Append is used to
append whatever you write/delete to(from) the end of the file.
FileAccess enum specifies whether you would like to read from the
file, write to the file or do both ; ReadWrite.
class WriteDemo
{
public static void Main()
{
Console.WriteLine("Enter the file you want to write to : ");
String path = Console.ReadLine();
46 | P a g e
Learn C# - do it yourself way... 2008
writer.Write(textToWrite);
writer.Close();
stream.Close();
}
}
The above program asks the user to enter the path, where he would
like to store the file. It then asks the user to enter some text to be
written to the file. A FileStream object is created and hooked to the
file in the specified path, with the Create FileMode and Write
access(as we want to write text to the file).
The writer object is now the tool that you would use to actually write
things to a file. You do so by calling the methods of the StreamWriter
object.
After you’re done with writing text to the file, it is very important to
remember that we must unhook the FileStream from the file. If you
forget to do this, even after the program is over, the file will remain
blocked by the FileStream, so no other program which needs access to
the file will be able to access it. To do so, we close the FileStream and
StreamWriter objects, by calling their Close() methods.
47 | P a g e
Learn C# - do it yourself way... 2008
class ReaderDemo
{
public static void Main()
{
FileStream stream = new FileStream("C:\\abc.txt", FileMode.Open,
FileAccess.Read);
StreamReader reader = new StreamReader(stream);
reader.Close();
}
}
To read from a file, one must first create a FileStream object and hook
it upto the file, open the file in read-mode. Next, we take a
StreamReader object and pass to its constructor the stream, we would
like to read from.
class ReaderDemo
{
public static void Main()
{
48 | P a g e
Learn C# - do it yourself way... 2008
reader.Close();
}
}
Given the above abc.txt file, we get the following output, when we
specify the offset = 12 bytes from the beginning.
49 | P a g e
Learn C# - do it yourself way... 2008
}
}
class DirectoryDemo
{
public static void Main()
{
DirectoryInfo dir = new DirectoryInfo("C:\\");
Console.WriteLine("Directory Name : " + dir.FullName);
Console.WriteLine("Last Access Time : " + dir.LastAccessTime);
Console.WriteLine("Creation Time : " + dir.CreationTime);
Console.WriteLine("Attributes : " + dir.Attributes);
}
}
50 | P a g e
Learn C# - do it yourself way... 2008
class EnumeratingDemo
{
public static void Main()
{
DirectoryInfo dir = new DirectoryInfo("C:\\");
51 | P a g e
Learn C# - do it yourself way... 2008
52 | P a g e
Learn C# - do it yourself way... 2008
10
Threads, Processes,
AppDomains and
Multi-threading
53 | P a g e