C sharp notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

C# Notes

History:
During the development of the .NET Framework, the class libraries were originally written using a managed
code compiler system named Simple Managed C (SMC). In January 1999, Anders Hejlsberg formed a team to build a new
language at the time called Cool, which stood for "C-like Object Oriented Language". Microsoft had considered keeping
the name "Cool" as the final name of the language, but chose not to do so for trademark reasons. By the time the .NET
project was publicly announced at the July 2000 Professional Developers Conference, the language had been renamed
C#, and the class libraries and ASP.NET runtime had been ported to C#.

Syntax:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
----------Program Instruction-----------
}
}
}

Example explained

Line 1: The using System line means that you are using the System library in your project. Which gives you some useful
classes like Console or functions/methods.

Line 2: Contains interfaces and classes that define generic collections, which allow users to create strongly typed
collections that provide better type safety.

Line 3: LINQ offers common syntax for querying any type of data source; for example, you can query an XML
document in the same way as you query a SQL database

Line 4: Contains classes that represent ASCII and Unicode character encodings; abstract base classes for converting
blocks of characters to and from blocks of bytes.

Line 5: The Task class represents a single operation that does not return a value and that usually executes
asynchronously.

Line 6: Namespace can be define as a Collection of classes and Objects which is used to keep separate one set of
names from another.

using System;

namespace HelloWorld

1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.ReadKey();

}
}
}

-----------------------------------------
Console.WriteLine("Hello World!");
Console.WriteLine("I am Learning C#");
Console.WriteLine("It is awesome!");
Console.WriteLine(3 + 3); // out put 6
-----------------------------
Comments:
// This is a comment
Console.WriteLine("Hello World!");

/* The code below will print the words Hello World


to the screen, and it is amazing */
Console.WriteLine("Hello World!");

-------------------------------------

In C#, there are different types of variables (defined with different keywords), for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -123
 double - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
 string - stores text, such as "Hello World". String values are surrounded by double quotes
 bool - stores values with two states: true or false

Data Type Size Description


int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
Stores whole numbers from -9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
bool 1 byte Stores true or false values
char 2 bytes Stores a single character/letter, surrounded by single quotes
2 bytes per
string Stores a sequence of characters, surrounded by double quotes
character
type variableName = value;

string name = "Saleem";


Console.WriteLine(name);

int myNum = 15;

2
Console.WriteLine(myNum);

float myNum = 5.75F; myNum = 15;


Console.WriteLine(myNum); Console.WriteLine(myNum);
double myNum = 19.99D; int myNum = 15;
Console.WriteLine(myNum); myNum = 20; // myNum is now 20
int myNum; Console.WriteLine(myNum);

-----------------------------------------------------
int myNum = 5;
double myDoubleNum = 5.99D;
char myLetter = 'D';
bool myBool = true;
string myText = "Hello";
--------------------------------------------------------
const int myNum = 15; -----------------------------------------
myNum = 20; // error
--------------------------------------------------------- int x = 5;
int y = 6;
string name = "Saleem"; Console.WriteLine(x + y);
Console.WriteLine("Hello " + name); ----------------------------------------------
----------------------------------------
int x = 5, y = 6, z = 50;
string firstName = "Muhammad "; Console.WriteLine(x + y + z);
string lastName = "Saleem"; ------------------------------------------------------------
string fullName = firstName + lastName;
Console.WriteLine(fullName);
bool isCSharpFun = true;
bool isFishTasty = false;
Console.WriteLine(isCSharpFun); // Outputs True
Console.WriteLine(isFishTasty); // Outputs False
----------------------------------------------------------

Runtime Input:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
string name;
char g;
int marks;

Console.WriteLine("Enter Your Name:");


name=Console.ReadLine();

Console.WriteLine("Enter your marks");


marks = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter Your grade");

3
g = Console.ReadKey().KeyChar;

Console.WriteLine("Name:" + name);
Console.WriteLine("Marks: " + marks);
Console.WriteLine("Grade: " + g);
Console.ReadKey();
}
}
}
------------------------------------------------------
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
float a;
double b;

Console.WriteLine("Enter Float Value");


a=Convert.ToSingle(Console.ReadLine());

Console.WriteLine("Enter Double value");


b = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Float value:" + a);


Console.WriteLine("Double value: " + b);

Console.ReadKey();
}
}
}

Arithmetic Operators:
+ - * / % ++ --

using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{

int a,b,res;

Console.WriteLine("Enter First Number");

a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Second Number");

b = Convert.ToInt32(Console.ReadLine());
res = a + b;
Console.WriteLine("Addition:" + res);
res = a - b;
Console.WriteLine("Subtraction:" + res);
res = a * b;
4
Console.WriteLine("Multiplication:" + res);
res = a / b;
Console.WriteLine("Division:" + res);
res = a % b;
Console.WriteLine("Remainder:" + res);

Console.ReadKey();
}
}
}

Assignment Operators:

= += -= *= /= %= ^=
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{

int a=10;

a += 2;
Console.WriteLine("Addition:" + a);
a -= 2;
Console.WriteLine("Subtraction:" + a);
a *= 2;
Console.WriteLine("Multiplication:" + a);
a /= 2;
Console.WriteLine("Division:" + a);
a %= 2;
Console.WriteLine("Remainder:" + a);

Console.ReadKey();
}
}
}

C# Type Casting

Type casting is when you assign a value of one data type to another type.

In C#, there are two types of casting:

 Implicit Casting (automatically) - converting a smaller type to a larger type size


char -> int -> long -> float -> double

 Explicit Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char

int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

Console.WriteLine(myInt); // Outputs 9
5
Console.WriteLine(myDouble); // Outputs 9
--------------------------------------
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int

Console.WriteLine(myDouble); // Outputs 9.78


Console.WriteLine(myInt); // Outputs 9
------------------------------------------------------------
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;

Console.WriteLine(Convert.ToString(myInt)); // convert int to string


Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int
Console.WriteLine(Convert.ToString(myBool)); // convert bool to string

Comparison Operators:
== != > < >= <=

Logical Operators:
&& || !

C# Math
Math.Max(x,y)
Math.Max(5, 10);

Math.Min(x,y)
Math.Min(5, 10);

Math.Sqrt(x)
Math.Sqrt(64);

Math.Abs(x)
Math.Abs(-4.7)

Math.Round()
Math.Round(9.99);

If Condition:
if (condition)
{
// block of code to be executed if the condition is True
}

Example:
using System;
namespace HelloWorld
6
{
class Program
{
static void Main(string[] args)
{

int n;

Console.WriteLine("Enter a Number");

n = Convert.ToInt32(Console.ReadLine());
if(n%2==0)
Console.WriteLine("Even Number");
if (n % 2 == 1)
Console.WriteLine("Odd Number");
Console.ReadKey();
}
}
}

If-else Statement:
if (condition)
{
// block of code to be executed if the condition is True
}
else
{
// block of code to be executed if the condition is False
}
Example:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{

int n;

Console.WriteLine("Enter a Number");

n = Convert.ToInt32(Console.ReadLine());
if(n%2==0)
Console.WriteLine("Even Number");
else
Console.WriteLine("Odd Number");
Console.ReadKey();
}
}
}

The else if Statement:


if (condition1)
{
// block of code to be executed if condition1 is True
}

7
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
else
{
// block of code to be executed if the condition1 is false and condition2 is False
}
Example:

using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{

int n;

Console.WriteLine("Enter a Number");

n = Convert.ToInt32(Console.ReadLine());
if(n>0)
Console.WriteLine("Positive Number");
else if(n<0)
Console.WriteLine("Negative Number");
else
Console.WriteLine("Zero");
Console.ReadKey();
}
}
}
Conditional Operator:

variable = (condition) ? expressionTrue : expressionFalse;

C# Switch Statements:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
Example:

using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
8
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
}
Console.ReadKey();
}
}
}

C# While Loop
while (condition)
{
// code block to be executed
}

Example:

int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}

The Do/While Loop:


do
{
// code block to be executed
}
while (condition);
Example:

int i = 0;
do
{
Console.WriteLine(i);
i++;
9
}
while (i < 5);

C# For Loop:
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}

Example:

for (int i = 0; i < 5; i++)


{
Console.WriteLine(i);
}

Nested Loops
for (int i = 1; i <= 2; ++i)
{
Console.WriteLine("Outer: " + i);

for (int j = 1; j <= 3; j++)


{
Console.WriteLine(" Inner: " + j);
}
}

The foreach Loop

There is also a foreach loop, which is used exclusively to loop through elements in an array (or other data
sets):

foreach (type variableName in arrayName)


{
// code block to be executed
}
Example:

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


foreach (string i in cars)
{
Console.WriteLine(i);
}

C# Break and Continue


for (int i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}
Console.WriteLine(i);
}

10
C# Continue
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
Console.WriteLine(i);
}

C# Arrays
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]);
---------------------------------------

int[] myNum = {10, 20, 30, 40};


-------------------------------------

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


for (int i = 0; i < cars.Length; i++)
{
Console.WriteLine(cars[i]);
}

Sort an Array

There are many array methods available, for example Sort(), which sorts an array alphabetically or in an
ascending order:

// Sort a string
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Array.Sort(cars);
foreach (string i in cars)
{
Console.WriteLine(i);
}
-----------------------------------

// Sort an int
int[] myNumbers = {5, 1, 8, 9};
Array.Sort(myNumbers);
foreach (int i in myNumbers)
{
Console.WriteLine(i);
}
-----------------------------------------

Two-Dimensional Arrays

To create a 2D array, add each array within its own set of curly braces, and insert a comma ( ,) inside the square
brackets:

int[,] numbers = { {1, 4, 2}, {3, 6, 8} };

11
foreach (int i in numbers)
{
Console.WriteLine(i);
}
---------------------------------------

int[,] numbers = { {1, 4, 2}, {3, 6, 8} };

for (int i = 0; i < numbers.GetLength(0); i++)


{
for (int j = 0; j < numbers.GetLength(1); j++)
{
Console.WriteLine(numbers[i, j]);
}
}
-----------------------------------------

C# Methods

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times.

Create a Method

A method is defined with the name of the method, followed by parentheses (). C# provides some pre-defined
methods, which you already are familiar with, such as Main(), but you can also create your own methods to
perform certain actions:

class Program
{
static void MyMethod()
{
// code to be executed
}
}

Example Explained

 MyMethod() is the name of the method


 static means that the method belongs to the Program class and not an object of the Program class. You will
learn more about objects and how to access methods through objects later in this tutorial.
 void means that this method does not have a return value. You will learn more about return values later in this
chapter

Call a Method

To call (execute) a method, write the method's name followed by two parentheses () and a semicolon;
12
In the following example, MyMethod() is used to print a text (the action), when it is called:

static void MyMethod()


{
Console.WriteLine("I just got executed!");
}

static void Main(string[] args)


{
MyMethod();
}

// Outputs "I just got executed!"

Example with parameters


static void MyMethod(string fname)
{
Console.WriteLine(fname + " Refsnes");
}

static void Main(string[] args)


{
MyMethod("Liam");
MyMethod("Jenny");
MyMethod("Anja");
}
Output:
Liam Refsnes
Jenny Refsnes
Anja Refsnes

Example:

static void MyMethod(string fname, int age)


{
Console.WriteLine(fname + " is " + age);
}

static void Main(string[] args)


{
MyMethod("Liam", 5);
MyMethod("Jenny", 8);
MyMethod("Anja", 31);
}

// Liam is 5
// Jenny is 8
// Anja is 31

Default Parameter Value


static void MyMethod(string country = "Norway")
{
Console.WriteLine(country);
}

13
static void Main(string[] args)
{
MyMethod("Sweden");
MyMethod("India");
MyMethod();
MyMethod("USA");
}

// Sweden
// India
// Norway
// USA

Return Values
static int MyMethod(int x)
{
return 5 + x;
}

static void Main(string[] args)


{
Console.WriteLine(MyMethod(3));
}

// Outputs 8 (5 + 3)

Named Arguments Example:


static void MyMethod(string child1, string child2, string child3)
{
Console.WriteLine("The youngest child is: " + child3);
}

static void Main(string[] args)


{
MyMethod(child3: "John", child1: "Liam", child2: "Liam");
}

// The youngest child is: John

Method Overloading
static int PlusMethodInt(int x, int y)
{
return x + y;
}

static double PlusMethodDouble(double x, double y)


{
return x + y;
}

static void Main(string[] args)


{
int myNum1 = PlusMethodInt(8, 5);
double myNum2 = PlusMethodDouble(4.3, 6.26);
Console.WriteLine("Int: " + myNum1);
Console.WriteLine("Double: " + myNum2);
}
---------------------------------

14
static int PlusMethod(int x, int y)
{
return x + y;
}

static double PlusMethod(double x, double y)


{
return x + y;
}

static void Main(string[] args)


{
int myNum1 = PlusMethod(8, 5);
double myNum2 = PlusMethod(4.3, 6.26);
Console.WriteLine("Int: " + myNum1);
Console.WriteLine("Double: " + myNum2);
}
------------------------------

C# - What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform operations on the data, while
object-oriented programming is about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the C# code DRY "Don't Repeat Yourself", and makes the code easier to maintain,
modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter development time

C# - What are Classes and Objects?

Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and objects:

15
class objects

Fruit Apple

Banana

Mango

Another example:

class objects

Car Volvo

Audi

Toyota

So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the variables and methods from the class.

Classes and Objects

You learned from the previous chapter that C# is an object-oriented programming language.

Everything in C# is associated with classes and objects, along with its attributes and methods. For example: in
real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and
brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a class named "Car" with a variable color:

class Car
{
string color = "red";
}

Multiple Objects
class Car
{
string color = "red";
static void Main(string[] args)
{
16
Car myObj1 = new Car();
Car myObj2 = new Car();
Console.WriteLine(myObj1.color);
Console.WriteLine(myObj2.color);
}
}

Using Multiple Classes

You can also create an object of a class and access it in another class. This is often used for better organization
of classes (one class has all the fields and methods, while the other class holds the Main() method (code to be
executed)).

 prog2.cs
 prog.cs

prog2.cs
class Car
{
public string color = "red";
}

prog.cs
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}

Class Members

Create a Car class with three class members: two fields and one method.

// The class
class MyClass
{
// Class members
string color = "red"; // field
int maxSpeed = 200; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
}

Fields
class Car
{
string color = "red";
int maxSpeed = 200;

static void Main(string[] args)


{

17
Car myObj = new Car();
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}

Example
class Car
{
string color;
int maxSpeed;

static void Main(string[] args)


{
Car myObj = new Car();
myObj.color = "red";
myObj.maxSpeed = 200;
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}

Constructors
A constructor is a special method that is used to initialize objects. The advantage of a constructor, is that it is called
when an object of a class is created. It can be used to set initial values for fields:

// Create a Car class


class Car
{
public string model; // Create a field

// Create a class constructor for the Car class


public Car()
{
model = "Mustang"; // Set the initial value for model
}

static void Main(string[] args)


{
Car Ford = new Car(); // Create an object of the Car Class (this will call the
constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
}

// Outputs "Mustang"

Constructor Parameters

Constructors can also take parameters, which is used to initialize fields.

The following example adds a string modelName parameter to the constructor. Inside the constructor we set
model to modelName (model=modelName). When we call the constructor, we pass a parameter to the constructor
("Mustang"), which will set the value of model to "Mustang":

18
Example
class Car
{
public string model;

// Create a class constructor with a parameter


public Car(string modelName)
{
model = modelName;
}

static void Main(string[] args)


{
Car Ford = new Car("Mustang");
Console.WriteLine(Ford.model);
}
}

// Outputs "Mustang"
--------------------------------------------------------------------------

Example
class Car
{
public string model;
public string color;
public int year;

// Create a class constructor with multiple parameters


public Car(string modelName, string modelColor, int modelYear)
{
model = modelName;
color = modelColor;
year = modelYear;
}

static void Main(string[] args)


{
Car Ford = new Car("Mustang", "Red", 1969);
Console.WriteLine(Ford.color + " " + Ford.year + " " + Ford.model);
}
}

// Outputs Red 1969 Mustang

Access Modifiers
Modifier Description

public The code is accessible for all classes

private The code is only accessible within the same class

protected The code is accessible within the same class, or in a class that is inherited from that class. You

19
will learn more about inheritance in a later chapter

The code is only accessible within its own assembly, but not from another assembly. You will
internal
learn more about this in a later chapter

Private Modifier

If you declare a field with a private access modifier, it can only be accessed within the same class:

class Car
{
private string model = "Mustang";

static void Main(string[] args)


{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}

The output will be:

Mustang
---------------------------------------------

If you try to access it outside the class, an error will occur:

Example
class Car
{
private string model = "Mustang";
}

class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}

The output will be:

'Car.model' is inaccessible due to its protection level


The field 'Car.model' is assigned but its value is never used

Public Modifier

If you declare a field with a public access modifier, it is accessible for all classes:

20
Example
class Car
{
public string model = "Mustang";
}

class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}

Properties and Encapsulation

Before we start to explain properties, you should have a basic understanding of "Encapsulation".

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you
must:

 declare fields/variables as private


 provide public get and set methods, through properties, to access and update the value of a private
field

Properties

You learned from the previous chapter that private variables can only be accessed within the same class (an
outside class has no access to it). However, sometimes we need to access them - and it can be done with
properties.

A property is like a combination of a variable and a method, and it has two methods: a get and a set method:

Example
class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}

class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);

21
}
}

The output will be:

Liam

Automatic Properties (Short Hand)

C# also provides a way to use short-hand / automatic properties, where you do not have to define the field for
the property, and you only have to write get; and set; inside the property.

The following example will produce the same result as the example above. The only difference is that there is
less code:

Example

Using automatic properties:

class Person
{
public string Name // property
{ get; set; }
}

class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}

The output will be:

Liam

Why Encapsulation?

 Better control of class members (reduce the possibility of yourself (or others) to mess up the code)
 Fields can be made read-only (if you only use the get method), or write-only (if you only use the set method)
 Flexible: the programmer can change one part of the code without affecting other parts
 Increased security of data

22
Inheritance (Derived and Base Class)

In C#, it is possible to inherit fields and methods from one class to another. We group the "inheritance concept"
into two categories:

 Derived Class (child) - the class that inherits from another class
 Base Class (parent) - the class being inherited from

To inherit from a class, use the : symbol.

In the example below, the Car class (child) inherits the fields and methods from the Vehicle class (parent):

class Vehicle // base class (parent)


{
public string brand = "Ford"; // Vehicle field
public void honk() // Vehicle method
{
Console.WriteLine("Tuut, tuut!");
}
}

class Car : Vehicle // derived class (child)


{
public string modelName = "Mustang"; // Car field
}

class Program
{
static void Main(string[] args)
{
// Create a myCar object
Car myCar = new Car();

// Call the honk() method (From the Vehicle class) on the myCar object
myCar.honk();

// Display the value of the brand field (from the Vehicle class) and the value of the
modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}

Polymorphism and Overriding Methods

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by
inheritance.

Like we specified in the previous chapter; Inheritance lets us inherit fields and methods from another class.
Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in
different ways.

For example, think of a base class called Animal that has a method called animalSound(). Derived classes of
Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound
(the pig oinks, and the cat meows, etc.):

23
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal // Derived class (child)


{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}

class Dog : Animal // Derived class (child)


{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
---------------------------------

Example
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal // Derived class (child)


{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}

class Dog : Animal // Derived class (child)


{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}

class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object

24
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}

The output will be:

The animal makes a sound


The animal makes a sound
The animal makes a sound
-------------------------------------------------------

class Animal // Base class (parent)


{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal // Derived class (child)


{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}

class Dog : Animal // Derived class (child)


{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}

class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}

The output will be:

25
The animal makes a sound
The pig says: wee wee
The dog says: bow wow

Abstract Classes and Methods

Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the
next chapter).

The abstract keyword is used for classes and methods:

 Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from
another class).

 Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the
derived class (inherited from).

Example
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}

// Derived class (inherit from Animal)


class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}

class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound(); // Call the abstract method
myPig.sleep(); // Call the regular method
}
}

26
Interfaces

Another way to achieve abstraction in C#, is with interfaces.

An interface is a completely "abstract class", which can only contain abstract methods and properties (with
empty bodies):

Example
// Interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}

// Pig "implements" the IAnimal interface


class Pig : IAnimal
{
public void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}

class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}

Notes on Interfaces:

 Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to
create an "IAnimal" object in the Program class)
 Interface methods do not have a body - the body is provided by the "implement" class
 On implementation of an interface, you must override all of its methods
 Interfaces can contain properties and methods, but not fields/variables
 Interface members are by default abstract and public
 An interface cannot contain a constructor (as it cannot be used to create objects)

Why And When To Use Interfaces?

1) To achieve security - hide certain details and only show the important details of an object (interface).

2) C# does not support "multiple inheritance" (a class can only inherit from one base class). However, it can be
achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple
interfaces, separate them with a comma (see example below).

27
Multiple Interfaces

To implement multiple interfaces, separate them with a comma:

Example
interface IFirstInterface
{
void myMethod(); // interface method
}

interface ISecondInterface
{
void myOtherMethod(); // interface method
}

// Implement multiple interfaces


class DemoClass : IFirstInterface, ISecondInterface
{
public void myMethod()
{
Console.WriteLine("Some text..");
}
public void myOtherMethod()
{
Console.WriteLine("Some other text...");
}
}

class Program
{
static void Main(string[] args)
{
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}

C# Enums

An enum is a special "class" that represents a group of constants (unchangeable/read-only variables).

To create an enum, use the enum keyword (instead of class or interface), and separate the enum items with a
comma:

class Program
{
enum Level
{
Low,
Medium,
High
}
static void Main(string[] args)
{
Level myVar = Level.Medium;
28
Console.WriteLine(myVar);
}
}

The output will be:

Medium
---------------------------------------
enum Months
{
January, // 0
February, // 1
March, // 2
April, // 3
May, // 4
June, // 5
July // 6
}

static void Main(string[] args)


{
int myNum = (int) Months.April;
Console.WriteLine(myNum);
}

The output will be:

C# Files

The File class has many useful methods for creating and getting information about files. For example:

Method Description
AppendText() Appends text at the end of an existing file
Copy() Copies a file
Create() Creates or overwrites a file
Delete() Deletes a file
Exists() Tests whether the file exists
ReadAllText() Reads the contents of a file
Replace() Replaces the contents of a file with the contents of another file
WriteAllText() Creates a new file and writes the contents to it. If the file already exists, it will
be overwritten.

Write To a File and Read It

In the following example, we use the WriteAllText() method to create a file named "filename.txt" and write
some content to it. Then we use the ReadAllText() method to read the contents of the file:

Example

29
using System.IO; // include the System.IO namespace

string writeText = "Hello World!"; // Create a text string


File.WriteAllText("filename.txt", writeText); // Create a file and write the content of
writeText to it

string readText = File.ReadAllText("filename.txt"); // Read the contents of the file


Console.WriteLine(readText); // Output the content

The output will be:

Hello World!

C# Exceptions

When executing C# code, different errors can occur: coding errors made by the programmer, errors due to
wrong input, or other unforeseeable things.

When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C#
will throw an exception (throw an error).

C# try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

Syntax
try
{
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors
}
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

The output will be:

Index was outside the bounds of the array.


30
Finally

The finally statement lets you execute code, after try...catch, regardless of the result:

Example
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
}
finally
{
Console.WriteLine("The 'try catch' is finished.");
}

The output will be:

Something went wrong.


The 'try catch' is finished.

The throw keyword

The throw statement allows you to create a custom error.

The throw statement is used together with an exception class. There are many exception classes available in
C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException,
etc:

Example
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else
{
Console.WriteLine("Access granted - You are old enough!");
}
}

static void Main(string[] args)


{
checkAge(15);
}

The error message displayed in the program will be:

31
System.ArithmeticException: 'Access denied - You must be at least 18 years old.'

32

You might also like