C sharp notes
C sharp notes
C sharp 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!");
-------------------------------------
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
2
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;
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.ReadKey();
}
}
}
Arithmetic Operators:
+ - * / % ++ --
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
int a,b,res;
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.
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
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();
}
}
}
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:
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++;
}
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:
Nested Loops
for (int i = 1; i <= 2; ++i)
{
Console.WriteLine("Outer: " + i);
There is also a foreach loop, which is used exclusively to loop through elements in an array (or other data
sets):
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]);
---------------------------------------
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:
11
foreach (int i in numbers)
{
Console.WriteLine(i);
}
---------------------------------------
C# Methods
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
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:
Example:
// Liam is 5
// Jenny is 8
// Anja is 31
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;
}
// Outputs 8 (5 + 3)
Method Overloading
static int PlusMethodInt(int x, int y)
{
return x + y;
}
14
static int PlusMethod(int x, int y)
{
return x + y;
}
C# - What is OOP?
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.
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
When the individual objects are created, they inherit all the variables and methods from the class.
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.
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);
}
}
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;
17
Car myObj = new Car();
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}
Example
class Car
{
string color;
int 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:
// Outputs "Mustang"
Constructor Parameters
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;
// Outputs "Mustang"
--------------------------------------------------------------------------
Example
class Car
{
public string model;
public string color;
public int year;
Access Modifiers
Modifier Description
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";
Mustang
---------------------------------------------
Example
class Car
{
private string model = "Mustang";
}
class Program
{
static void Main(string[] args)
{
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:
20
Example
class Car
{
public string model = "Mustang";
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}
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:
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
}
}
Liam
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
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);
}
}
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
In the example below, the Car class (child) inherits the fields and methods from the Vehicle class (parent):
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 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");
}
}
Example
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
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();
}
}
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();
}
}
25
The animal makes a sound
The pig says: wee wee
The dog says: bow wow
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).
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");
}
}
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
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)
}
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)
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
Example
interface IFirstInterface
{
void myMethod(); // interface method
}
interface ISecondInterface
{
void myOtherMethod(); // interface method
}
class Program
{
static void Main(string[] args)
{
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
C# Enums
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);
}
}
Medium
---------------------------------------
enum Months
{
January, // 0
February, // 1
March, // 2
April, // 3
May, // 4
June, // 5
July // 6
}
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.
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
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).
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.
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 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 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!");
}
}
31
System.ArithmeticException: 'Access denied - You must be at least 18 years old.'
32