C# Programming notes for level 3, computer engineering, NPUI Bamenda
C# Programming notes for level 3, computer engineering, NPUI Bamenda
C# is pronounced "C-Sharp".
It is an object-oriented programming language created by Microsoft that runs
on the .NET Framework.
C# has roots from the C family, and the language is close to other popular
languages like C++ and Java.
C# is used for:
Mobile applications
Desktop applications
Web applications
Web services
Web sites
Games
Database applications
Why Use C#?
It is one of the most popular programming language in the world
It is easy to learn and simple to use
It has a huge community support
C# is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs.
C# Syntax
Line 2: A blank line. C# ignores white space. However, multiple lines makes
the code more readable.
1
Line 3: namespace is used to organize your code, and it is a container for
classes and other namespaces.
Line 4: The curly braces {} marks the beginning and the end of a block of code.
Line 5: class is a container for data and methods, which brings functionality to
your program. Every line of code that runs in C# must be inside a class. In our
example, we named the class Program.
Line 7: Another thing that always appear in a C# program, is the Main method.
Any code inside its curly brackets {} will be executed. You don't have to
understand the keywords before and after Main
WriteLine or Write
The difference is that WriteLine() prints the output on a new line each time,
while Write() prints on the same line (note that you should remember to add
spaces when needed, for better readability):
C# Variables
In C#, there are different types of variables (defined with different keywords),
for example:
2
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
To create a variable, you must specify the type and assign it a value:
Syntax
type variableName = value;
Display Variables
The WriteLine() method is often used to display variable values to the console
window.
C# Identifiers
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
3
Names can contain letters, digits and the underscore character (_)
Names must begin with a letter
Names should start with a lowercase letter and it cannot contain
whitespace
Names are case sensitive ("myVar" and "myvar" are different variables)
Reserved words (like C# keywords, such as int or double) cannot be used
as names
C# Data Types
A data type specifies the size and type of variable values. It is important to use
the correct data type for the corresponding variable; to avoid errors, to save time
and memory, but it will also make your code more maintainable and readable.
The most common data types are:
Numbers
Integer types stores whole numbers, positive or negative (such as 123 or -456),
without decimals. Valid types are int and long. Which type you should use,
depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one
or more decimals. Valid types are float and double.
Integer Types
Int
The int data type can store whole numbers from -2147483648 to 2147483647.
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the
value. Note that you should end the value with an "L":
4
Floating Point Types
You should use a floating point type whenever you need a number with a
decimal, such as 9.99 or 3.14515.
Float
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038.
Note that you should end the value with an "F":
Double
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308.
A floating point number can also be a scientific number with an "e" to indicate
the power of 10:
Booleans
A boolean data type is declared with the bool keyword and can only take the
values true or false. Boolean values are mostly used for conditional testing.
Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
Strings
5
The string data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:
C# Type Casting
Type casting is when you assign a value of one data type to another type.
Implicit Casting
Explicit Casting
Why Conversion?
6
Many times, there's no need for type conversion, but sometimes you have to.
Get User Input
In the following example, the user can input his or hers username, which is
stored in the variable userName. Then we print the value of userName:
Example
Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and store it in
the variable
// Print the value of the variable (userName), which will display the input value
Example
Example
C# Assignment Operators
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
8
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
C# Comparison Operators
9
== Equal to x == y
!= Not equal x != y
C# Logical Operators
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns true if both statements are true x < 5 && x < 10
10
! Logical not Reverse the result, returns false if the !(x < 5 && x < 10)
result is true
Math.Max(x,y)
The Math.Max(x,y) method can be used to find the highest value of x and y:
Example
Math.Max(5, 10);
Math.Min(x,y)
The Math.Min(x,y) method can be used to find the lowest value of of x and y:
Example
Math.Min(5, 10);
Math.Sqrt(x)
Example
Math.Sqrt(64);
Math.Abs(x)
11
Math.Round() rounds a number to the nearest whole number:
Example
Math.Round(9.99);
C# Strings
String Length
Example
Other Methods
Example
12
The + operator can be used between strings to combine them. This is
called concatenation:
Example
You can also use the string.Concat() method to concatenate two strings:
Example
Example
You can access the characters in a string by referring to its index number inside
square brackets [].
13
Example
You can also find the index position of a specific character in a string, by using
the IndexOf() method:
Example
Example
// Full name
string name = "John Doe";
Special Characters
14
Because strings must be written within quotes, C# will misunderstand this
string, and generate an error:
string txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string
characters:
\\ \ Backslash
Example
string txt = "We are the so-called \"Vikings\" from the north.";
Example
15
Example
Code Result
\n New Line
\t Tab
\b Backspace
C# Booleans
Very often, in programming, you will need a data type that can only have one
of two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, C# has a bool data type, which can take the values true or false.
Boolean Values
A boolean type is declared with the bool keyword and can only take the
values true or false:
16
Example
You can use these conditions to perform different actions for different
decisions.
The if Statement
17
Syntax
if (condition)
In the example below, we test two values to find out if 20 is greater than 18. If
the condition is True, print some text:
Example
Example
int x = 20;
int y = 18;
if (x > y)
}
The else Statement
Use the else statement to specify a block of code to be executed if the condition
is False.
18
Syntax
if (condition)
{
else
{
// block of code to be executed if the condition is False
}
Example
int time = 8;
if (time < 6)
Console.WriteLine("Good day.");
else
{
Console.WriteLine("Good evening.");
Use the else if statement to specify a new condition if the first condition
is False.
19
Syntax
if (condition1)
{
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
else
Example
Console.WriteLine("Good morning.");
}
else if (time < 20)
Console.WriteLine("Good day.");
20
else
{
Console.WriteLine("Good evening.");
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
int time = 20;
if (time < 18)
{
Console.WriteLine("Good day.");
else
Console.WriteLine("Good evening.");
21
You can simply write:
Example
Console.WriteLine(result);
C# Switch Statements
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression)
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
22
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break and default keywords will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:
Example
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;
23
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no
need for more testing.
A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.
The default Keyword
The default keyword is optional and specifies some code to run if there is no
case match:
Example
int day = 4;
switch (day)
{
case 6:
24
Console.WriteLine("Today is Saturday.");
break;
case 7:
Console.WriteLine("Today is Sunday.");
break;
default:
break;
}
Loops
Loops are handy because they save time, reduce errors, and they make code
more readable.
C# While Loop
The while loop loops through a block of code as long as a specified condition
is True:
Syntax
while (condition)
{
25
In the example below, the code in the loop will run, over and over again, as long
as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.
Syntax
do
while (condition);
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:
26
Example
int i = 0;
do
Console.WriteLine(i);
i++;
C# For Loop
When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:
Syntax
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
Console.WriteLine(i);
There is also a foreach loop, which is used exclusively to loop through elements
in an array:
Syntax
The following example outputs all elements in the cars array, using
a foreach loop:
Example
Console.WriteLine(i);
}
Console.WriteLine(i);
}
28
ARRAYS
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value
Create an Array
string[] cars;
To insert values to it, we can use an array literal - place the values in a comma-
separated list, inside curly braces:
Example
Console.WriteLine(cars[0]);
29
// Outputs Volvo
Example
cars[0] = "Opel";
Example
cars[0] = "Opel";
Console.WriteLine(cars[0]);
Array Length
To find out how many elements an array has, use the Length property:
Example
Console.WriteLine(cars.Length);
// Outputs 4
You can loop through the array elements with the for loop, and use
the Length property to specify how many times the loop should run.
30
Example
Console.WriteLine(cars[i]);
There is also a foreach loop, which is used exclusively to loop through elements
in an array:
Syntax
The following example outputs all elements in the cars array, using
a foreach loop:
Example
Console.WriteLine(i);
31
The example above can be read like this: for each string element (called i - as
in index) in cars, print out the value of i.
If you compare the for loop and foreach loop, you will see that
the foreach method is easier to write, it does not require a counter (using
the Length property), and it is more readable.
Sort Arrays
There are many array methods available, for example Sort(), which sorts an
array alphabetically or in an ascending order:
Example
// Sort a string
Console.WriteLine(i);
}
// Sort an int
int[] myNumbers = {5, 1, 8, 9};
Array.Sort(myNumbers);
32
{
Console.WriteLine(i);
}
System.Linq Namespace
Other useful array methods, such as Min, Max, and Sum, can be found in
the System.Linq namespace:
Example
using System;
using System.Linq;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
If you are familiar with C#, you might have seen arrays created with
the new keyword, and perhaps you have seen arrays with a specified size as
well. In C#, there are different ways to create an array:
// Create an array of four elements, omitting the new keyword, and without
specifying the size
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Method
34
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:
Example
// code to be executed
Example Explained
Call a Method
35
In the following example, MyMethod() is used to print a text (the action), when
it is called:
Example
}
static void Main(string[] args)
{
MyMethod();
They are specified after the method name, inside the parentheses. You can add
as many parameters as you want, just separate them with a comma.
The following example has a method that takes a string called fname as
parameter. When the method is called, we pass along a first name, which is used
inside the method to print the full name:
36
Example
{
MyMethod("Liam");
MyMethod("Jenny");
MyMethod("Anja");
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
When a parameter is passed to the method, it is called an argument. So, from
the example above: fname is a parameter,
while Liam, Jenny and Anja are arguments.
Default Parameter Value
You can also use a default parameter value, by using the equals sign (=). If we
call the method without an argument, it uses the default value ("Norway"):
37
Example
Console.WriteLine(country);
MyMethod("India");
MyMethod();
MyMethod("USA");
// Sweden
// India
// Norway
// USA
A parameter with a default value, is often known as an "optional parameter".
From the example above, country is an optional parameter and "Norway" is the
default value.
Multiple Parameters
38
Example
{
MyMethod("Liam", 5);
MyMethod("Jenny", 8);
MyMethod("Anja", 31);
// Liam is 5
// Jenny is 8
// Anja is 31
Note that when you are working with multiple parameters, the method call must
have the same number of arguments as there are parameters, and the arguments
must be passed in the same order.
Return Values
The void keyword, used in the examples above, indicates that the method
should not return a value. If you want the method to return a value, you can use
a primitive data type (such as int or double) instead of void, and use
the return keyword inside the method:
39
Example
return 5 + x;
{
Console.WriteLine(MyMethod(3));
}
// Outputs 8 (5 + 3)
Example
return x + y;
Console.WriteLine(MyMethod(5, 3));
// Outputs 8 (5 + 3)
You can also store the result in a variable (recommended, as it is easier to read
and maintain):
40
Example
return x + y;
{
int z = MyMethod(5, 3);
Console.WriteLine(z);
// Outputs 8 (5 + 3)
Named Arguments
Example
{
MyMethod(child3: "John", child1: "Liam", child2: "Liam");
}
41
// The youngest child is: John
Named arguments are especially useful when you have multiple parameters
with default values, and you only want to specify one of them when you call it:
Example
Console.WriteLine(child3);
}
static void Main(string[] args)
{
MyMethod("child3");
// John
Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:
Example
int MyMethod(int x)
float MyMethod(float x)
42
Consider the following example, which have two methods that add numbers of
different type:
Example
{
return x + y;
return x + y;
}
{
int myNum1 = PlusMethodInt(8, 5);
double myNum2 = PlusMethodDouble(4.3, 6.26);
Instead of defining two methods that should do the same thing, it is better to
overload one.
Example
43
{
return x + y;
}
return x + y;
44
C# CLASSES
C# - What is OOP?
Note: The "Don't Repeat Yourself" (DRY) principle is about reducing the
repetition of code. You should extract out the codes that are common for the
application, and place them at a single place and reuse them instead of repeating
it.
Classes and objects are the two main aspects of object-oriented programming.
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.
45
Create a Class
class Car
An object is created from a class. We have already created the class named Car,
so now we can use this to create objects.
To create an object of Car, specify the class name, followed by the object name,
and use the keyword new:
Example
Create an object called "myObj" and use it to print the value of color:
class Car
46
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
Note that we use the dot syntax (.) to access variables/fields inside a class
(myObj.color).
Multiple Objects
Example
class Car
Console.WriteLine(myObj1.color);
Console.WriteLine(myObj2.color);
}
}
Using Multiple Classes
47
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)).
class Car
{
public string color = "red";
class Program
{
}}
The public keyword is called an access modifier, which specifies that
the color variable/field of Car is accessible for other classes as well, such
as Program.
Object Methods
Methods normally belongs to a class, and they define how an object of a class
behaves.
Just like with fields, you can access methods with the dot syntax. However, note
that the method must be public. And remember that we use the name of the
method followed by two parantheses () and a semicolon ; to call (execute) the
method:
48
Example
class Car
{
{
Console.WriteLine("The car is going as fast as it can!");
}
}
Why did we declare the method as public, and not static? The reason is simple:
a static method can be accessed without creating an object of the class,
while public methods can only be accessed by objects.
Constructors
Example
Create a constructor:
49
// Create a Car class
class Car
{
public Car()
Car Ford = new Car(); // Create an object of the Car Class (this will call the
constructor)
}
}
// Outputs "Mustang"
Note that the constructor name must match the class name, and it cannot have
a return type (like void or int).
Also note that the constructor is called when the object is created.
Constructors Save Time
Access Modifiers
50
By now, you are quite familiar with the public keyword that appears in many of
our examples:
The public keyword is an access modifier, which is used to set the access
level/visibility for classes, fields, methods and properties.
Modifier Description
protected The code is accessible within the same class, or in a class that is
inherited from that class.
internal The code is only accessible within its own assembly, but not from
another assembly.
Private Modifier
If you declare a field with a private access modifier, it can only be accessed
within the same class:
51
Example
class Car
{
{
Car Ford = new Car("Mustang");
Console.WriteLine(Ford.model);
Mustang
Example
class Car
{
}
class Program
52
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
Public Modifier
If you declare a field with a public access modifier, it is accessible for all
classes:
Example
class Car
{
public string model = "Mustang";
}
class Program
53
}
}
The output will be:
Mustang
To control the visibility of class members (the security level of each individual
class and class member).
To achieve "Encapsulation" - which is the process of making sure that
"sensitive" data is hidden from users. This is done by declaring fields as private.
Note: By default, all members of a class are private if you don't specify an
access modifier:
Encapsulation
Properties
You have already learned 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.
class Person
{
{
get { return name; } // get method
set { name = value; } // set method
}
Example explained
The Name property is associated with the name field. It is a good practice to use
the same name for both the property and the private field, but with an uppercase
first letter.
The set method assigns a value to the name variable. The value keyword
represents the value we assign to the property.
Now we can use the Name property to access and update the private field of
the Person class:
Example
class Person
{
private string name; // field
55
public string Name // property
{
get { return name; }
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?
56
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
In the example below, the Car class (child) inherits the fields and methods from
the Vehicle class (parent):
Example
{
Console.WriteLine("Tuut, tuut!");
}
class Program
{
57
static void Main(string[] args)
{
// Create a myCar object
// 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);
}
}
Why And When To Use "Inheritance"?
- It is useful for code reusability: reuse fields and methods of an existing class
when you create a new class.
The sealed Keyword
If you don't want other classes to inherit from a class, use the sealed keyword:
...
}
class Car : Vehicle
{
...
58
}
The error message will be something like this:
Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.
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.):
Example
59
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
Now we can create Pig and Dog objects and call the animalSound() method on
both of them:
Example
}
}
60
{
public void animalSound()
{
{
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
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
61
}}
The output will be:
The animal makes a sound
The animal makes a sound
The animal makes a sound
The output from the example above was probably not what was expected. That
is because the base class method overrides the derived class method, when they
share the same name.
However, C# provides an option to override the base class method, by adding
the virtual keyword to the method inside the base class, and by using
the override keyword for each derived class methods:
Example
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
}
}
62
class Dog : Animal // Derived class (child)
{
public override void animalSound()
class Program
{
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
Example
interface IFirstInterface
interface ISecondInterface
{
void myOtherMethod(); // interface method
}
// Implement multiple interfaces
Console.WriteLine("Some text..");
}
public void myOtherMethod()
64
}
}
class Program
myObj.myMethod();
myObj.myOtherMethod();
}
}
Files
The File class from the System.IO namespace, allows us to work with files:
Example
The File class has many useful methods for creating and getting information
about files. For example:
Method Description
65
AppendText() Appends text at the end of an existing file
66
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
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).
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
67
Syntax
try
{
catch (Exception e)
{
// Block of code to handle errors
}
Console.WriteLine(myNumbers[10]); // error!
If an error occurs, we can use try...catch to catch the error and execute some
code to handle it.
In the following example, we use the variable inside the catch block (e) together
with the built-in Message property, which outputs a message that describes the
exception:
Example
try
68
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
catch (Exception e)
Console.WriteLine(e.Message);
}
The output will be:
Example
try
{
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
69
Something went wrong.
Finally
The finally statement lets you execute code, after try...catch, regardless of the
result:
Example
try
catch (Exception e)
{
}
finally
{
Console.WriteLine("The 'try catch' is finished.");
}
70
The throw statement is used together with an exception class. There are many
exception classes available in
C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeExcepti
on, TimeOutException, etc:
71
Example
}
else
}
}
{
checkAge(15);
}
72