C# IMP Notes (E-Next - In) PDF
C# IMP Notes (E-Next - In) PDF
C# IMP Notes (E-Next - In) PDF
By the help of C# programming language, we can develop different types of secured and
robust applications:
o Window applications
o Web applications
o Distributed applications
C# is approved as a standard by ECMA and ISO. C# is designed for CLI (Common Language
Infrastructure). CLI is a specification that describes executable code and runtime
environment.
C++ vs. C#
There are many differences and similarities between C++ programming language and C#. A
list of top differences between C++ and C# are given below:
No. C++ C#
https://E-next.in
management is handled
manually.
4) In C++, pointers can be used In C#, pointers can be used only in unsafe mode.
anywhere in a program.
7) C++ programming can be used to C# programming can be used to create console applic
create console applications. applications, Mobile applications, etc.
Java vs C#
There are many differences and similarities between Java and C#. A list of top differences
between Java and C# are given below:
No. Java C#
4) In java, built-in data types In C#, built-in data types that are passed by value are called simple
that are passed by value are
https://E-next.in
called primitive types.
C# History
History of C# language is interesting to know. Here we are going to discuss brief history
of C# language.
https://E-next.in
It is based on C++ and Java, but it has many additional extensions used to perform
component oriented programming approach.
C# has evolved much since their first release in the year 2002. It was introduced with .NET
Framework 1.0 and the current version of C# is 5.0.
Let's see the important features introduced in each version of C# are given below.
C# Features
C# is object oriented programming language. It provides a lot of features that are given
below.
1. Simple
3. Object oriented
4. Type safe
5. Interoperability
7. Component oriented
9. Rich Library
https://E-next.in
C# Example: Hello World
In C# programming language, a simple "hello world" program can be written by multiple
ways. Let's see the top 4 ways to create a simple C# example:
o Simple Example
o Using System
o Using namespace
C# Simple Example
1. class Program
2. {
3. static void Main(string[] args)
4. {
5. System.Console.WriteLine("Hello World!");
6. }
7. }
https://E-next.in
Output:
Hello World!
C# Variable
A variable is a name of memory location. It is used to store data. Its value can be changed
and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
1. type variable_list;
1. int i, j;
2. double d;
3. float f;
4. char ch;
Here, i, j, d, f, ch are variables and int, double, float, char are data types.
We can also provide values while declaring the variables as given below:
https://E-next.in
1. int i=2,j=4; //declaring 2 variable of integer type
2. float f=40.2;
3. char ch='B';
C# Data Types
A data type specifies the type of data that a variable can store such as integer, floating,
character etc.
C# operators
https://E-next.in
An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise etc.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators
o Unary Operators
o Ternary Operators
o Misc Operators
https://E-next.in
Precedence of Operators in C#
The precedence of operator specifies that which operator will be evaluated first and next.
The associativity specifies the operators direction to be evaluated, it may be left to right
or right to left.
C# Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc.
<td< td=""></td<>
https://E-next.in
switch this throw true try typeof
volatile while
Some identifiers which have special meaning in context of code are called as Contextual
Keywords.
C# if-else
In C# programming, the if statement is used to test the condition. There are various types
of if statements in C#.
o if statement
o if-else statement
o nested if statement
o if-else-if ladder
C# IF Statement
The C# if statement tests the condition. It is executed if condition is true.
Syntax:
1. if(condition){
2. //code to be executed
3. }
https://E-next.in
C# If Example
1. using System;
2. public class IfExample
3. {
4. public static void Main(string[] args)
5. {
6. int num = 10;
7. if (num % 2 == 0)
8. {
9. Console.WriteLine("It is even number");
10. }
11.
12. }
13. }
https://E-next.in
Output:
It is even number
C# switch
The C# switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement in C#.
Syntax:
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
break;
https://E-next.in
C# Switch Example
using System;
Console.WriteLine("Enter a number:");
switch (num)
Output:
Enter a number:
10
It is 10
https://E-next.in
Output:
Enter a number:
55
Not 10, 20 or 30
C# For Loop
The C# for loop is used to iterate a part of the program several times. If the number of iteration is fixed,
it is recommended to use for loop than while or do-while loops.
The C# for loop is same as C/C++. We can initialize variable, check condition and increment/decrement
value.
Syntax:
//code to be executed
Flowchart:
using System;
https://E-next.in
public class ForExample
for(int i=1;i<=10;i++){
Console.WriteLine(i);
Output:
10
https://E-next.in
In C#, we can use for loop inside another for loop, it is known as nested for loop. The inner loop is
executed fully when outer loop is executed one time. So if outer loop and inner loop are executed 3
times, inner loop will be executed 3 times for each outer loop i.e. total 9 times.
using System;
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
Console.WriteLine(i+" "+j);
Output:
11
12
13
21
22
23
https://E-next.in
31
32
33
If we use double semicolon in for loop, it will be executed infinite times. Let's see a simple example of
infinite for loop in C#.
using System;
for (; ;)
Output:
https://E-next.in
Infinitive For Loop
ctrl+c
C# While Loop
In C#, while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop than for loop.
Syntax:
1. while(condition){
2. //code to be executed
3. }
Flowchart:
1. using System;
https://E-next.in
2. public class WhileExample
3. {
4. public static void Main(string[] args)
5. {
6. int i=1;
7. while(i<=10)
8. {
9. Console.WriteLine(i);
10. i++;
11. }
12. }
13. }
Output:
1
2
3
4
5
6
7
8
9
10
C# Do-While Loop
The C# do-while loop is used to iterate a part of the program several times. If the number
of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop.
The C# do-while loop is executed at least once because condition is checked after loop
body.
Syntax:
1. do{
2. //code to be executed
3. }while(condition);
https://E-next.in
C# do-while Loop Example
Let's see a simple example of C# do-while loop to print the table of 1.
1. using System;
2. public class DoWhileExample
3. {
4. public static void Main(string[] args)
5. {
6. int i = 1;
7.
8. do{
9. Console.WriteLine(i);
10. i++;
11. } while (i <= 10) ;
12.
13. }
14. }
Output:
1
2
https://E-next.in
3
4
5
6
7
8
9
10
C# Break Statement
The C# break is used to break loop or switch statement. It breaks the current flow of the program at the
given condition. In case of inner loop, it breaks only inner loop.
Syntax:
jump-statement;
break;
Flowchart:
Let's see a simple example of C# break statement which is used inside the loop.
using System;
https://E-next.in
public static void Main(string[] args)
if (i == 5)
break;
Console.WriteLine(i);
Output:
The C# break statement breaks inner loop only if you use break statement inside the inner loop. Let's
see the example code:
https://E-next.in
using System;
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break;
Console.WriteLine(i+" "+j);
Output:
11
12
13
21
31
32
33
https://E-next.in
C# Continue Statement
The C# continue statement is used to continue loop. It continues the current flow of the program and
skips the remaining code at specified condition. In case of inner loop, it continues only inner loop.
Syntax:
jump-statement;
continue;
using System;
for(int i=1;i<=10;i++){
if(i==5){
continue;
Console.WriteLine(i);
Output:
https://E-next.in
1
10
C# Continue Statement continues inner loop only if you use continue statement inside the inner loop.
using System;
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
continue;
https://E-next.in
}
Console.WriteLine(i+" "+j);
Output:
11
12
13
21
23
31
32
33
C# Goto Statement
The C# goto statement is also known jump statement. It is used to transfer control to the
other part of the program. It unconditionally jumps to the specified label.
It can be used to transfer control from deeply nested loop or switch case label.
Currently, it is avoided to use goto statement in C# because it makes the program complex.
1. using System;
https://E-next.in
2. public class GotoExample
3. {
4. public static void Main(string[] args)
5. {
6. ineligible:
7. Console.WriteLine("You are not eligible to vote!");
8.
9. Console.WriteLine("Enter your age:\n");
10. int age = Convert.ToInt32(Console.ReadLine());
11. if (age < 18){
12. goto ineligible;
13. }
14. else
15. {
16. Console.WriteLine("You are eligible to vote!");
17. }
18. }
19. }
Output:
C# Comments
The C# comments are statements that are not executed by the compiler. The comments in C#
programming can be used to provide explanation of the code, variable, method or class. By the help of
comments, you can hide the program code also.
https://E-next.in
Single Line comment
The single line comment starts with // (double slash). Let's see an example of single line comment in C#.
using System;
Console.WriteLine(x);
Output:
10
The C# multi line comment is used to comment multiple lines of code. It is surrounded by slash and
asterisk (/* ..... */). Let's see an example of multi line comment in C#.
https://E-next.in
using System;
int x=20;
Console.WriteLine(x);
Output:
20
C# Arrays
Like other programming languages, array in C# is a group of similar types of elements that
have contiguous memory location. In C#, array is an object of base type System.Array. In
C#, array index starts from 0. We can store only fixed set of elements in C# array.
Advantages of C# Array
o Code Optimization (less code)
https://E-next.in
o Random Access
Disadvantages of C# Array
o Fixed size
C# Array Types
There are 3 types of arrays in C# programming:
2. Multidimensional Array
3. Jagged Array
Let's see a simple example of C# array, where we are going to declare, initialize and
traverse array.
1. using System;
2. public class ArrayExample
3. {
4. public static void Main(string[] args)
5. {
6. int[] arr = new int[5];//creating array
7. arr[0] = 10;//initializing array
8. arr[2] = 20;
9. arr[4] = 30;
https://E-next.in
10.
11. //traversing array
12. for (int i = 0; i < arr.Length; i++)
13. {
14. Console.WriteLine(arr[i]);
15. }
16. }
17. }
Output:
10
0
20
0
30
C# Multidimensional Arrays
The multidimensional array is also known as rectangular arrays in C#. It can be two
dimensional or three dimensional. The data is stored in tabular form (row * column) which
is also known as matrix.
To create multidimensional array, we need to use comma inside the square brackets. For
example:
1. using System;
2. public class MultiArrayExample
3. {
4. public static void Main(string[] args)
5. {
6. int[,] arr=new int[3,3];//declaration of 2D array
7. arr[0,1]=10;//initialization
8. arr[1,2]=20;
https://E-next.in
9. arr[2,0]=30;
10.
11. //traversal
12. for(int i=0;i<3;i++){
13. for(int j=0;j<3;j++){
14. Console.Write(arr[i,j]+" ");
15. }
16. Console.WriteLine();//new line at each row
17. }
18. }
19. }
Output:
0 10 0
0 0 20
30 0 0
C# Jagged Arrays
In C#, jagged array is also known as "array of arrays" because its elements are arrays. The element size
of jagged array can be different.
Let's see an example to declare jagged array that has two elements.
Let's see an example to initialize jagged array. The size of elements can be different.
https://E-next.in
arr[0] = new int[4];
Here, size of elements in jagged array is optional. So, you can write above code as given below:
Let's see a simple example of jagged array in C# which declares, initializes and traverse jagged arrays.
https://E-next.in
arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
System.Console.Write(arr[i][j]+" ");
System.Console.WriteLine();
Output:
11 21 56 78
42 61 37 41 59 63
https://E-next.in
new int[] { 2, 5 }
};
Let's see a simple example of jagged array which initializes the jagged arrays upon declaration.
new int[] { 2, 5 }
};
System.Console.Write(arr[i][j]+" ");
System.Console.WriteLine();
https://E-next.in
}
Output:
11 21 56 78
2 5 6 7 98 5
25
Since C# is an object-oriented language, program is designed using objects and classes in C#.
C# Object
In C#, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data and behavior
means functionality.
Object is an instance of a class. All the members of the class can be accessed through object.
https://E-next.in
In this example, Student is the type and s1 is the reference variable that refers to the instance of
Student class. The new keyword allocates memory at runtime.
C# Class
In C#, class is a group of similar objects. It is a template from which objects are created. It can have
fields, methods, constructors etc.
Let's see an example of class that has two fields: id and name. It creates instance of the class, initializes
the object and prints the object value.
using System;
https://E-next.in
public static void Main(string[] args)
s1.id = 101;
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
Output:
101
Sonoo Jaiswal
Let's see another example of class where we are having Main() method in another class. In such case,
class must be public.
using System;
https://E-next.in
class TestStudent{
s1.id = 101;
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
Output:
101
Sonoo Jaiswal
Let's see another example of C# class where we are initializing and displaying object through method.
using System;
https://E-next.in
{
id = i;
name = n;
class TestStudent{
s1.insert(101, "Ajeet");
s2.insert(102, "Tom");
s1.display();
s2.display();
Output:
101 Ajeet
102 Tom
https://E-next.in
C# Class Example 4: Store and Display Employee Information
using System;
id = i;
name = n;
salary = s;
class TestEmployee{
e1.insert(101, "Sonoo",890000f);
https://E-next.in
e2.insert(102, "Mahesh", 490000f);
e1.display();
e2.display();
Output:
C# Constructor
In C#, constructor is a special method which is invoked automatically at the time of object creation. It is
used to initialize the data members of new object generally. The constructor in C# has the same name as
class or struct.
Default constructor
Parameterized constructor
C# Default Constructor
A constructor which has no argument is known as default constructor. It is invoked at the time of
creating object.
https://E-next.in
C# Default Constructor Example: Having Main() within class
using System;
public Employee()
Output:
Let's see another example of default constructor where we are having Main() method in another class.
https://E-next.in
using System;
public Employee()
class TestEmployee{
Output:
C# Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide different
values to distinct objects.
using System;
https://E-next.in
public class Employee
id = i;
name = n;
salary = s;
class TestEmployee{
e1.display();
e2.display();
https://E-next.in
}
Output:
C# Destructor
A destructor works opposite to constructor, It destructs the objects of classes. It can be
defined only once in a class. Like constructors, it is invoked automatically.
1. using System;
2. public class Employee
3. {
4. public Employee()
5. {
6. Console.WriteLine("Constructor Invoked");
7. }
8. ~Employee()
9. {
10. Console.WriteLine("Destructor Invoked");
11. }
12. }
13. class TestEmployee{
14. public static void Main(string[] args)
15. {
16. Employee e1 = new Employee();
17. Employee e2 = new Employee();
https://E-next.in
18. }
19. }
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
C# this
In c# programming, this is a keyword that refers to the current instance of the class. There
can be 3 main usage of this keyword in C#.
o It can be used to refer current class instance variable. It is used if field names
(instance variables) and parameter names are same, that is why both can be
distinguish easily.
C# this example
Let's see the example of this keyword in C# that refers to the fields of current class.
1. using System;
2. public class Employee
3. {
4. public int id;
5. public String name;
6. public float salary;
7. public Employee(int id, String name,float salary)
8. {
9. this.id = id;
10. this.name = name;
11. this.salary = salary;
12. }
13. public void display()
https://E-next.in
14. {
15. Console.WriteLine(id + " " + name+" "+salary);
16. }
17. }
18. class TestEmployee{
19. public static void Main(string[] args)
20. {
21. Employee e1 = new Employee(101, "Sonoo", 890000f);
22. Employee e2 = new Employee(102, "Mahesh", 490000f);
23. e1.display();
24. e2.display();
25.
26. }
27. }
Output:
C# static
In C#, static is a keyword or modifier that belongs to the type not instance. So instance is
not required to access the static members. In C#, static can be field, method, constructor,
class, properties, operator and event.
C# Static Field
A field which is declared as static, is called static field. Unlike instance field which gets
memory each time whenever you create object, there is only one copy of static field created
in the memory. It is shared to all the objects.
https://E-next.in
It is used to refer the common property of all objects such as rateOfInterest in case of
Account, companyName in case of Employee etc.
1. using System;
2. public class Account
3. {
4. public int accno;
5. public String name;
6. public static float rateOfInterest=8.8f;
7. public Account(int accno, String name)
8. {
9. this.accno = accno;
10. this.name = name;
11. }
12.
13. public void display()
14. {
15. Console.WriteLine(accno + " " + name + " " + rateOfInterest);
16. }
17. }
18. class TestAccount{
19. public static void Main(string[] args)
20. {
21. Account a1 = new Account(101, "Sonoo");
22. Account a2 = new Account(102, "Mahesh");
23. a1.display();
24. a2.display();
25.
26. }
27. }
Output:
https://E-next.in
C# static class
The C# static class is like the normal class but it cannot be instantiated. It can have only
static members. The advantage of static class is that it provides you guarantee that instance
of static class cannot be created.
1. using System;
2. public static class MyMath
3. {
4. public static float PI=3.14f;
5. public static int cube(int n){return n*n*n;}
6. }
7. class TestMyMath{
8. public static void Main(string[] args)
9. {
10. Console.WriteLine("Value of PI is: "+MyMath.PI);
11. Console.WriteLine("Cube of 3 is: " + MyMath.cube(3));
12. }
13. }
Output:
C# static constructor
https://E-next.in
C# static constructor is used to initialize static fields. It can also be used to perform any
action that is to be performed only once. It is invoked automatically before first instance is
created or any static member is referenced.
1. using System;
2. public class Account
3. {
4. public int id;
5. public String name;
6. public static float rateOfInterest;
7. public Account(int id, String name)
8. {
9. this.id = id;
10. this.name = name;
11. }
12. static Account()
13. {
14. rateOfInterest = 9.5f;
15. }
16. public void display()
17. {
18. Console.WriteLine(id + " " + name+" "+rateOfInterest);
19. }
20. }
21. class TestEmployee{
22. public static void Main(string[] args)
23. {
24. Account a1 = new Account(101, "Sonoo");
25. Account a2 = new Account(102, "Mahesh");
26. a1.display();
https://E-next.in
27. a2.display();
28.
29. }
30. }
Output:
C# Structs
In C#, classes and structs are blueprints that are used to create instance of a class. Structs are used for
lightweight objects such as Color, Rectangle, Point etc.
Unlike class, structs in C# are value type than reference type. It is useful if you have data that is not
intended to be modified after creation of struct.
C# Struct Example
Let's see a simple example of struct Rectangle which has two data members width and height.
using System;
https://E-next.in
public static void Main()
r.width = 4;
r.height = 5;
Output:
Let's see another example of struct where we are using constructor to initialize data and method to
calculate area of rectangle.
using System;
width = w;
https://E-next.in
height = h;
r.areaOfRectangle();
Output:
C# Enum
Enum in C# is also known as enumeration. It is used to store a set of named constants such as season,
days, month, size etc. The enum constants are also known as enumerators. Enum in C# can be declared
within or outside class and structs.
Enum constants has default values which starts from 0 and incremented to one by one. But we can
change the default value.
Points to remember
https://E-next.in
enum has fixed set of constants
C# Enum Example
using System;
int x = (int)Season.WINTER;
int y = (int)Season.SUMMER;
Output:
WINTER = 0
SUMMER = 2
https://E-next.in
C# enum example changing start index
using System;
int x = (int)Season.WINTER;
int y = (int)Season.SUMMER;
Output:
WINTER = 10
SUMMER = 12
using System;
https://E-next.in
{
public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
int x = (int)Days.Sun;
int y = (int)Days.Mon;
int z = (int)Days.Sat;
Output:
Sun = 0
Mon = 1
Sat = 6
using System;
public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
https://E-next.in
public static void Main()
Console.WriteLine(s);
Output:
Sun
Mon
Tue
Wed
Thu
Fri
Sat
using System;
public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
https://E-next.in
{
Console.WriteLine(d);
Output:
Sun
Mon
Tue
Wed
Thu
Fri
Sat
C# Properties
C# Properites doesn't have storage location. C# Properites are extension of fields and accessed like
fields.
The Properties have accessors that are used to set, get or compute their values.
Usage of C# Properties
https://E-next.in
C# Properties can be read-only or write-only.
We make fields of the class private, so that fields can't be accessed from outside the class directly. Now
we are forced to use C# properties for setting or getting values.
C# Properties Example
using System;
get
return name;
set
name = value;
class TestEmployee{
https://E-next.in
Employee e1 = new Employee();
Output:
using System;
get
return name;
set
https://E-next.in
{
class TestEmployee{
e1.Name = "Sonoo";
Output:
using System;
public Employee()
https://E-next.in
{
counter++;
get
return counter;
class TestEmployee{
Output:
No. of Employees: 3
https://E-next.in
C# Inheritance
In C#, inheritance is a process in which one object acquires all the properties and behaviors of its parent
object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which is
defined in other class.
In C#, the class which inherits the members of another class is called derived class and the class whose
members are inherited is called base class. The derived class is the specialized class for the base class.
Advantage of C# Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there is no need to define
the member again. So less code is required in the class.
When one class inherits another class, it is known as single level inheritance. Let's see the example of
single level inheritance which inherits the fields only.
using System;
https://E-next.in
public float bonus = 10000;
class TestInheritance{
Output:
Salary: 40000
Bonus: 10000
In the above example, Employee is the base class and Programmer is the derived class.
using System;
https://E-next.in
public class Animal
class TestInheritance2{
d1.eat();
d1.bark();
Output:
Eating...
Barking...
When one class inherits another class which is further inherited by another class, it is known as multi
level inheritance in C#. Inheritance is transitive so the last derived class acquires all the members of all
its base classes.
https://E-next.in
Let's see the example of multi level inheritance in C#.
using System;
class TestInheritance2{
d1.eat();
d1.bark();
d1.weep();
Output:
https://E-next.in
Eating...
Barking...
Weeping...
C# Method Overriding
If derived class defines same method as defined in its base class, it is known as method
overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide
specific implementation of the method which is already provided by its base class.
To perform method overriding in C#, you need to use virtual keyword with base class
method and override keyword with derived class method.
1. using System;
2. public class Animal{
3. public virtual void eat(){
4. Console.WriteLine("Eating...");
5. }
6. }
7. public class Dog: Animal
8. {
9. public override void eat()
10. {
11. Console.WriteLine("Eating bread...");
12. }
13. }
14. public class TestOverriding
15. {
16. public static void Main()
https://E-next.in
17. {
18. Dog d = new Dog();
19. d.eat();
20. }
21. }
Output:
Eating bread...
C# Base
In C#, base keyword is used to access fields, constructors and methods of base class.
You can use base keyword within instance method, constructor or instance property accessor only. You
can't use it inside the static method.
We can use the base keyword to access the fields of the base class within derived class. It is useful if
base and derived classes have the same fields. If derived class doesn't define same field, there is no
need to use base keyword. Base class field can be directly accessed by the derived class.
Let's see the simple example of base keyword in C# which accesses the field of base class.
using System;
https://E-next.in
{
Console.WriteLine(base.color);
Console.WriteLine(color);
d.showColor();
Output:
white
black
https://E-next.in
By the help of base keyword, we can call the base class method also. It is useful if base and derived
classes defines same method. In other words, if method is overridden. If derived class doesn't define
same method, there is no need to use base keyword. Base class method can be directly called by the
derived class method.
Let's see the simple example of base keyword which calls the method of base class.
using System;
Console.WriteLine("eating...");
base.eat();
Console.WriteLine("eating bread...");
https://E-next.in
d.eat();
Output:
eating...
eating bread...
Whenever you inherit the base class, base class constructor is internally invoked. Let's see the example
of calling base constructor.
using System;
public Animal(){
Console.WriteLine("animal...");
public Dog()
Console.WriteLine("dog...");
https://E-next.in
public class TestOverriding
Output:
animal...
dog...
C# Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a
greek word. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation and
polymorphism.
There are two types of polymorphism in C#: compile time polymorphism and runtime polymorphism.
Compile time polymorphism is achieved by method overloading and operator overloading in C#. It is also
known as static binding or early binding. Runtime polymorphism in achieved by method overriding
which is also known as dynamic binding or late binding.
https://E-next.in
Let's see a simple example of runtime polymorphism in C#.
using System;
Console.WriteLine("eating...");
Console.WriteLine("eating bread...");
a.eat();
Output:
https://E-next.in
eating bread...
Let's see a another example of runtime polymorphism in C# where we are having two derived classes.
using System;
Console.WriteLine("drawing...");
Console.WriteLine("drawing rectangle...");
https://E-next.in
{
Console.WriteLine("drawing circle...");
Shape s;
s = new Shape();
s.draw();
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
Output:
drawing...
drawing rectangle...
drawing circle...
https://E-next.in
Runtime Polymorphism can't be achieved by data members in C#. Let's see an example where we are
accessing the field by reference variable which refers to the instance of derived class.
using System;
Console.WriteLine(d.color);
Output:
White
https://E-next.in
C# Sealed
C# sealed keyword applies restrictions on the class and method. If you create a sealed
class, it cannot be derived. If you create a sealed method, it cannot be overridden.
C# Sealed class
C# sealed class cannot be derived by any class. Let's see an example of sealed class in C#.
1. using System;
2. sealed public class Animal{
3. public void eat() { Console.WriteLine("eating..."); }
4. }
5. public class Dog: Animal
6. {
7. public void bark() { Console.WriteLine("barking..."); }
8. }
9. public class TestSealed
10. {
11. public static void Main()
12. {
13. Dog d = new Dog();
14. d.eat();
15. d.bark();
16.
17.
18. }
19. }
Output:
Compile Time Error: 'Dog': cannot derive from sealed type 'Animal'
C# Interface
https://E-next.in
Interface in C# is a blueprint of a class. It is like abstract class because all the methods
which are declared inside the interface are abstract methods. It cannot have method body
and cannot be instantiated.
Its implementation must be provided by class or struct. The class or struct which
implements the interface, must provide the implementation of all the methods declared
inside the interface.
C# interface example
Let's see the example of interface in C# which has draw() method. Its implementation is
provided by two classes: Rectangle and Circle.
1. using System;
2. public interface Drawable
3. {
4. void draw();
5. }
6. public class Rectangle : Drawable
7. {
8. public void draw()
9. {
10. Console.WriteLine("drawing rectangle...");
11. }
12. }
13. public class Circle : Drawable
14. {
15. public void draw()
16. {
17. Console.WriteLine("drawing circle...");
18. }
19. }
20. public class TestInterface
21. {
22. public static void Main()
23. {
24. Drawable d;
25. d = new Rectangle();
https://E-next.in
26. d.draw();
27. d = new Circle();
28. d.draw();
29. }
30. }
Output:
drawing ractangle...
drawing circle...
C# Abstract
Abstract classes are the way to achieve abstraction in C#. Abstraction in C# is the process to hide the
internal details and showing functionality only. Abstraction can be achieved by two ways:
Abstract class
Interface
Abstract class and interface both can have abstract methods which are necessary for abstraction.
Abstract Method
A method which is declared abstract and has no body is called abstract method. It can be declared inside
the abstract class only. Its implementation must be provided by derived classes. For example:
An abstract method in C# is internally a virtual method so it can be overridden by the derived class.
You can't use static and virtual modifiers in abstract method declaration.
https://E-next.in
C# Abstract class
In C#, abstract class is a class which is declared abstract. It can have abstract and non-abstract methods.
It cannot be instantiated. Its implementation must be provided by derived classes. Here, derived class is
forced to provide the implementation of all the abstract methods.
Let's see an example of abstract class in C# which has one abstract method draw(). Its implementation is
provided by derived classes: Rectangle and Circle. Both classes have different implementation.
using System;
Console.WriteLine("drawing rectangle...");
https://E-next.in
{
Console.WriteLine("drawing circle...");
Shape s;
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
Output:
drawing ractangle...
drawing circle...
C# Namespaces
Namespaces in C# are used to organize too many classes so that it can be easy to handle the application.
https://E-next.in
In a simple C# program, we use System.Console where System is the namespace and Console is the
class. To access the class of a namespace, we need to use namespacename.classname. We can use using
keyword so that we don't have to use complete name all the time.
In C#, global namespace is the root namespace. The global::System will always refer to the namespace
"System" of .Net Framework.
C# namespace example
Let's see a simple example of namespace which contains one class "Program".
using System;
namespace ConsoleApplication1
class Program
Console.WriteLine("Hello Namespace!");
Output:
Hello Namespace!
https://E-next.in
C# namespace example: by fully qualified name
Let's see another example of namespace in C# where one namespace program accesses another
namespace program.
using System;
namespace First {
namespace Second
https://E-next.in
h1.sayHello();
h2.sayHello();
Output:
Let's see another example of namespace where we are using "using" keyword so that we don't have to
use complete name for accessing a namespace program.
using System;
using First;
using Second;
namespace First {
namespace Second
https://E-next.in
{
h1.sayHello();
w1.sayWelcome();
Output:
Hello Namespace
Welcome Namespace
C# Strings
In C#, string is an object of System.String class that represent sequence of characters.
We can perform many operations on strings such as concatenation, comparision, getting
substring, search, trim, replacement etc.
string vs String
In C#, string is keyword which is an alias for System.String class. That is why string and
String are equivalent. We are free to use any naming convention.
https://E-next.in
1. string s1 = "hello";//creating string using string keyword
2. String s2 = "welcome";//creating string using String class
C# String Example
1. using System;
2. public class StringExample
3. {
4. public static void Main(string[] args)
5. {
6. string s1 = "hello";
7.
8. char[] ch = { 'c', 's', 'h', 'a', 'r', 'p' };
9. string s2 = new string(ch);
10.
11. Console.WriteLine(s1);
12. Console.WriteLine(s2);
13. }
14. }
Output:
hello
csharp
C# String methods
Method Name Description
Compare(String, String) It is used to compares two specified String objects. It returns an int
their relative position in the sort order.
https://E-next.in
CompareTo(String) It is used to compare this instance with a specified String object. It
this instance precedes, follows, or appears in the same position in th
specified string.
Copy(String) It is used to create a new instance of String with the same value as
CopyTo(Int32, Char[], Int32, It is used to copy a specified number of characters from a specifi
Int32) instance to a specified position in an array of Unicode characters.
EndsWith(String) It is used to check that the end of this string instance matches the s
Equals(String, String) It is used to determine that two specified String objects have the sam
Format(String, Object) It is used to replace one or more format items in a specified stri
representation of a specified object.
GetEnumerator() It is used to retrieve an object that can iterate through the individua
string.
https://E-next.in
Insert(Int32, String) It is used to return a new string in which a specified string is inse
index position.
IsNullOrEmpty(String) It is used to indicate that the specified string is null or an Empty str
LastIndexOf(Char) It is used to report the zero-based index position of the last occurr
character within String.
LastIndexOfAny(Char[]) It is used to report the zero-based index position of the last occurren
of one or more characters specified in a Unicode array.
Normalize() It is used to return a new string whose textual value is the same
whose binary representation is in Unicode normalization form C.
PadRight(Int32) It is used to return a new string that left-aligns the characters in thi
them with spaces on the right.
https://E-next.in
Remove(Int32) It is used to return a new string in which all the characters in the
beginning at a specified position and continuing through the last p
deleted.
Replace(String, String) It is used to return a new string in which all occurrences of a spe
current instance are replaced with another specified string.
Split(Char[]) It is used to split a string into substrings that are based on the chara
ToLowerInvariant() It is used to return convert String into lowercase using the casing ru
culture.
https://E-next.in
TrimStart(Char[]) It is used to remove all leading occurrences of a set of characters sp
from the current String object.
C# Exception Handling
Exception Handling in C# is a process to handle runtime errors. We perform exception handling so that
normal flow of the application can be maintained even after runtime errors.
In C#, exception is an event or object which is thrown at runtime. All exceptions the derived from
System.Exception class. It is a runtime error which can be handled. If we don't handle the exception, it
prints exception message and terminates the program.
Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed event after
exception.
C# Exception Classes
All the exception classes in C# are derived from System.Exception class. Let's see the list of C# common
exception classes.
Exception Description
https://E-next.in
System.IO.IOException handles the Input Output errors.
System.FieldAccessException handles the error generated by invalid private or protected field access.
try
catch
finally, and
throw
Moreover, we can create user-defined exception which we will learn in next chapters.
C# try/catch
In C# programming, exception handling is performed by try/catch statement. The try block in C# is used
to place the code that may throw exception. The catch block is used to handled the exception. The catch
block must be preceded by try block.
using System;
https://E-next.in
public static void Main(string[] args)
int a = 10;
int b = 0;
int x = a/b;
Output:
C# try/catch example
using System;
try
int a = 10;
int b = 0;
int x = a / b;
https://E-next.in
}
Output:
C# finally
C# finally block is used to execute important code which is to be executed whether exception is handled
or not. It must be preceded by catch or try block.
using System;
try
int a = 10;
int b = 0;
https://E-next.in
int x = a / b;
Output:
using System;
try
int a = 10;
int b = 0;
https://E-next.in
int x = a / b;
Output:
C# Collections
In C#, collection represents group of objects. By the help of collections, we can perform various
operations on objects such as
store object
update object
delete object
retrieve object
sort object
We can store objects in array or collection. Collection has advantage over array. Array has size limit but
objects stored in collection can grow or shrink dynamically.
https://E-next.in
Types of Collections in C#
There are 3 ways to work with collections. The three namespaces are given below:
System.Collections.Generic classes
System.Collections.Concurrent classes
1) System.Collections.Generic classes
List
Stack
Queue
LinkedList
HashSet
SortedSet
Dictionary
SortedDictionary
SortedList
2) System.Collections classes
https://E-next.in
These classes are legacy. It is suggested now to use System.Collections.Generic classes. The
System.Collections namespace has following classes:
ArrayList
Stack
Queue
Hashtable
C# Stack<T>
C# Stack<T> class is used to push and pop elements. It uses the concept of Stack that
arranges elements in LIFO (Last In First Out) order. It can have duplicate elements. It is
found in System.Collections.Generic namespace.
C# Stack<T> example
Let's see an example of generic Stack<T> class that stores elements using Push() method,
removes elements using Pop() method and iterates elements using for-each loop.
1. using System;
2. using System.Collections.Generic;
3.
4. public class StackExample
5. {
6. public static void Main(string[] args)
7. {
8. Stack<string> names = new Stack<string>();
9. names.Push("Sonoo");
10. names.Push("Peter");
11. names.Push("James");
12. names.Push("Ratan");
13. names.Push("Irfan");
14.
15. foreach (string name in names)
16. {
17. Console.WriteLine(name);
https://E-next.in
18. }
19.
20. Console.WriteLine("Peek element: "+names.Peek());
21. Console.WriteLine("Pop: "+ names.Pop());
22. Console.WriteLine("After Pop, Peek element: " + names.Peek());
23.
24. }
25. }
Output:
Sonoo
Peter
James
Ratan
Irfan
Peek element: Irfan
Pop: Irfan
After Pop, Peek element: Ratan
C# Queue<T>
C# Queue<T> class is used to Enqueue and Dequeue elements. It uses the concept of
Queue that arranges elements in FIFO (First In First Out) order. It can have duplicate
elements. It is found in System.Collections.Generic namespace.
C# Queue<T> example
Let's see an example of generic Queue<T> class that stores elements using Enqueue()
method, removes elements using Dequeue() method and iterates elements using for-each
loop.
1. using System;
2. using System.Collections.Generic;
3.
4. public class QueueExample
5. {
6. public static void Main(string[] args)
7. {
8. Queue<string> names = new Queue<string>();
9. names.Enqueue("Sonoo");
10. names.Enqueue("Peter");
https://E-next.in
11. names.Enqueue("James");
12. names.Enqueue("Ratan");
13. names.Enqueue("Irfan");
14.
15. foreach (string name in names)
16. {
17. Console.WriteLine(name);
18. }
19.
20. Console.WriteLine("Peek element: "+names.Peek());
21. Console.WriteLine("Dequeue: "+ names.Dequeue());
22. Console.WriteLine("After Dequeue, Peek element: " + names.Peek());
23. }
24. }
Output:
Sonoo
Peter
James
Ratan
Irfan
Peek element: Sonoo
Dequeue: Sonoo
After Dequeue, Peek element: Peter
C# HashSet<T>
C# HashSet class can be used to store, remove or view elements. It does not store
duplicate elements. It is suggested to use HashSet class if you have to store only unique
elements. It is found in System.Collections.Generic namespace.
C# HashSet<T> example
Let's see an example of generic HashSet<T> class that stores elements using Add() method
and iterates elements using for-each loop.
1. using System;
2. using System.Collections.Generic;
3.
https://E-next.in
4. public class HashSetExample
5. {
6. public static void Main(string[] args)
7. {
8. // Create a set of strings
9. var names = new HashSet<string>();
10. names.Add("Sonoo");
11. names.Add("Ankit");
12. names.Add("Peter");
13. names.Add("Irfan");
14. names.Add("Ankit");//will not be added
15.
16. // Iterate HashSet elements using foreach loop
17. foreach (var name in names)
18. {
19. Console.WriteLine(name);
20. }
21. }
22. }
Output:
Sonoo
Ankit
Peter
Irfan
C# SortedList<TKey, TValue>
C# SortedList<TKey, TValue> is an array of key/value pairs. It stores values on the basis of
key. The SortedList<TKey, TValue> class contains unique keys and maintains ascending
order on the basis of key. By the help of key, we can easily search or remove elements. It is
found in System.Collections.Generic namespace.
https://E-next.in
C# SortedList<TKey, TValue> vs SortedDictionary<TKey,
TValue>
SortedList<TKey, TValue> class uses less memory than SortedDictionary<TKey, TValue>. It
is recommended to use SortedList<TKey, TValue> if you have to store and retrieve
key/valye pairs. The SortedDictionary<TKey, TValue> class is faster than SortedList<TKey,
TValue> class if you perform insertion and removal for unsorted data.
1. using System;
2. using System.Collections.Generic;
3.
4. public class SortedDictionaryExample
5. {
6. public static void Main(string[] args)
7. {
8. SortedList<string, string> names = new SortedList<string, string>();
9. names.Add("1","Sonoo");
10. names.Add("4","Peter");
11. names.Add("5","James");
12. names.Add("3","Ratan");
13. names.Add("2","Irfan");
14. foreach (KeyValuePair<string, string> kv in names)
15. {
16. Console.WriteLine(kv.Key+" "+kv.Value);
17. }
18. }
19. }
Output:
1 Sonoo
2 Irfan
3 Ratan
4 Peter
5 James
https://E-next.in
C# Properties
C# Properites doesn't have storage location. C# Properites are extension of fields and
accessed like fields.
The Properties have accessors that are used to set, get or compute their values.
Usage of C# Properties
1. C# Properties can be read-only or write-only.
3. We make fields of the class private, so that fields can't be accessed from outside the
class directly. Now we are forced to use C# properties for setting or getting values.
C# Properties Example
1. using System;
2. public class Employee
3. {
4. private string name;
5.
6. public string Name
7. {
8. get
9. {
10. return name;
11. }
12. set
13. {
14. name = value;
15. }
16. }
17. }
18. class TestEmployee{
19. public static void Main(string[] args)
20. {
21. Employee e1 = new Employee();
22. e1.Name = "Sonoo Jaiswal";
https://E-next.in
23. Console.WriteLine("Employee Name: " + e1.Name);
24.
25. }
26. }
Output:
C# Delegates
In C#, delegate is a reference to the method. It works like function pointer in C and C++.
But it is objected-oriented, secured and type-safe than function pointer.
For static method, delegate encapsulates method only. But for instance method, it
encapsulates method and instance both.
C# Delegate Example
Let's see a simple example of delegate in C# which calls add() and mul() methods.
1. using System;
2. delegate int Calculator(int n);//declaring delegate
3.
4. public class DelegateExample
5. {
6. static int number = 100;
7. public static int add(int n)
8. {
9. number = number + n;
10. return number;
11. }
12. public static int mul(int n)
13. {
https://E-next.in
14. number = number * n;
15. return number;
16. }
17. public static int getNumber()
18. {
19. return number;
20. }
21. public static void Main(string[] args)
22. {
23. Calculator c1 = new Calculator(add);//instantiating delegate
24. Calculator c2 = new Calculator(mul);
25. c1(20);//calling method using delegate
26. Console.WriteLine("After c1 delegate, Number is: " + getNumber());
27. c2(3);
28. Console.WriteLine("After c2 delegate, Number is: " + getNumber());
29.
30. }
31. }
Output:
Declaring Delegates
Delegate declaration determines the methods that can be referenced by the
delegate. A delegate can refer to a method, which has the same signature
as that of the delegate.
The preceding delegate can be used to reference any method that has a
single string parameter and returns an int type variable.
https://E-next.in
delegate <return type> <delegate-name> <parameter list>
Instantiating Delegates
Once a delegate type is declared, a delegate object must be created with
the new keyword and be associated with a particular method. When
creating a delegate, the argument passed to the new expression is written
similar to a method call, but without the arguments to the method. For
example:
using System;
https://E-next.in
return num;
}
public static int getNum()
{
return num;
}
When the above code is compiled and executed, it produces the following
result:
Value of Num: 35
Value of Num: 175
Multicasting of a Delegate
Delegate objects can be composed using the "+" operator. A composed
delegate calls the two delegates it was composed from. Only delegates of
the same type can be composed. The "-" operator can be used to remove a
component delegate from a composed delegate.
https://E-next.in
Using this property of delegates you can create an invocation list of
methods that will be called when a delegate is invoked. This is
called multicasting of a delegate. The following program demonstrates
multicasting of a delegate:
using System;
https://E-next.in
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
nc += nc2;
//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following
result:
Value of Num: 75
Using Delegates
The following example demonstrates the use of delegate. The
delegate printString can be used to reference method that takes a string as
input and returns nothing.
We use this delegate to call two methods, the first prints the string to the
console, and the second one prints it to a file:
using System;
using System.IO;
namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
https://E-next.in
// delegate declaration
public delegate void printString(string s);
https://E-next.in
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following
result:
.net Framework
https://E-next.in
Components of .Net Framework 3.5
Before going to the next session on Visual Studio.Net, let us go through at
the various components of the .Net framework 3.5. The following table
describes the components of the .Net framework 3.5 and the job they
perform:
It provides guidelines for declaring, using, and managing types at runtime, and
cross-language communication.
https://E-next.in
Metadata is the binary information describing the program, which is either stored
in a portable executable file (PE) or in the memory. Assembly is a logical unit
consisting of the assembly manifest, type metadata, IL code, and a set of
resources like image files.
ASP.NET is the web development model and AJAX is an extension of ASP.NET for
developing and implementing AJAX functionality. ASP.NET AJAX contains the
components that allow the developer to update data on a website without a
complete reload of the page.
(8) ADO.NET
It is the technology used for working with data and databases. It provides access
to data sources like SQL server, OLE DB, XML etc. The ADO.NET allows
connection to data sources for retrieving, manipulating, and updating data.
It provides a separation between the user interface and the business logic. It
helps in developing visually stunning interfaces using documents, media, two and
three dimensional graphics, animations, and more.
https://E-next.in
(11) Windows Communication Foundation (WCF)
It provides safety for accessing resources and sharing personal information on the
internet.
(13) LINQ
Net Framework is a platform that provides tools and technologies to develop Windows, Web
and Enterprise applications. It mainly contains two components,
Programmatically, when our program needs memory, CLR allocates the memory for scope
and de-allocates the memory if the scope is completed.
Language Compilers (e.g. C#, VB.Net, J#) will convert the Code/Program to Microsoft
Intermediate Language (MSIL) intern this will be converted to Native Code by CLR. See
the below Fig.
https://E-next.in
There are currently over 15 language compilers being built by Microsoft and other
companies also producing the code that will execute under CLR.
This is also called as Base Class Library and it is common for all types of applications i.e. the
way you access the Library Classes and Methods in VB.NET will be the same in C#, and it is
common for all other languages in .NET.
The following are different types of applications that can make use of .net class library.
1. Windows Application.
2. Console Application
3. Web Application.
5. Windows Services.
In short, developers just need to import the BCL in their language code and use its
predefined methods and properties to implement common and complex functions like
reading and writing to file, graphic rendering, database interaction, and XML document
manipulation.
Below are the few more concepts that we need to know and understand as part of this .Net
framework.
It describes set of data types that can be used in different .Net languages in common. (i.e),
CTS ensures that objects written in different .Net languages can interact with each other.
For Communicating between programs written in any .NET complaint language, the types
have to be compatible on the basic level.
https://E-next.in
The common type system supports two general categories of types:
Value types:
Value types directly contain their data, and instances of value types are either allocated on
the stack or allocated inline in a structure. Value types can be built-in (implemented by the
runtime), user-defined, or enumerations.
Reference types:
Reference types store a reference to the value's memory address, and are allocated on the
heap. Reference types can be self-describing types, pointer types, or interface types. The
type of a reference type can be determined from values of self-describing types. Self-
describing types are further split into arrays and class types. The class types are user-
defined classes, boxed value types, and delegates.
It is a sub set of CTS and it specifies a set of rules that needs to be adhered or satisfied by
all language compilers targeting CLR. It helps in cross language inheritance and cross
language debugging.
It describes the minimal and complete set of features to produce code that can be hosted by
CLR. It ensures that products of compilers will work properly in .NET environment.
Sample Rules:
3. Definition of static members and this is a subset of the CTS which all
.NET languages are expected to support.
4. Microsoft has defined CLS which are nothing but guidelines that language
to follow so that it can communicate with other .NET languages in a
seamless manner.
https://E-next.in