Sunteți pe pagina 1din 116

What is C#

C# is pronounced as "C-Sharp". It is an object-oriented programming language provided by


Microsoft that runs on .Net Framework.

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

o Web service applications

o Database applications etc.

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# programming language is influenced by C++, Java, Eiffel, Modula-3, Pascal etc.


languages.

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#

1) C++ is a general purpose, case- C# is pronounced as "C-Sharp". It is an


sensitive, free-form programming object-oriented programming language provided by
language that supports object- Microsoft that runs on
oriented, procedural and .Net Framework.
generic programming.

2) In C++, multiple inheritance is In C#, multiple inheritance is not possible.


possible.

3) In C++, memory In C#, memory management is handled automatically.

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.

5) C++ programming is based C# programming is based on Component and OOPs con


on OOPs concept.

6) C++ is a programming language C# is a programming language that rarely used outside W


that runs on all platforms.

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#

1) Java is a high level, robust, C# is an object-oriented programming language developed by


secured and object-oriented that runs on .Net Framework.
programming language
developed by Oracle.

2) Java programming language C# programming language is designed to be run on the Common


is designed to be run on a Runtime (CLR).
Java platform, by the help
of Java Runtime
Environment (JRE).

3) Java type safety is safe. C# type safety is unsafe.

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.

5) Arrays in Java are direct Arrays in C# are specialization of System.


specialization of Object.

6) Java does not C# supports conditional compilation using preprocessor directives.


support conditional
compilation.

7) Java doesn't support goto C# supports goto statement.


statement.

8) Java doesn't C# supports multiple inheritance using class.


support multiple
inheritance through class. It
can be achieved by interfaces
in java

9) Java doesn't C# supports structures and unions.


support structures and
unions.

10) Java supports checked C# supports unchecked exception.


exception and unchecked
exception.

C# History
History of C# language is interesting to know. Here we are going to discuss brief history
of C# language.

C# is pronounced as "C-Sharp". It is an object-oriented programming language provided


by Microsoft that runs on .Net Framework.

Anders Hejlsberg is known as the founder 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

2. Modern programming language

3. Object oriented

4. Type safe

5. Interoperability

6. Scalable and Updateable

7. Component oriented

8. Structured programming language

9. Rich Library

10. Fast speed

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 public modifier

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.

The basic variable type available in C# can be categorized as:

Variable Type Example

Decimal types decimal

Boolean types True or false value, as assigned

Integral types int, char, byte, short, long

Floating point types float and double

Nullable types Nullable data types

Let's see the syntax to declare a variable:

1. type variable_list;

The example of declaring variable is given below:

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.

There are 3 types of data types in C# language.

Types Data Types

Value Data Type int, char, float, Boolean, etc

Reference Data Type String, Class, Object and Interface

Pointer Data Type Pointers

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.

There are following types of operators to perform different types of operations in C#


language.

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.

Let's understand the precedence by the example given below:

1. int data= 10+ 5*5


The "data" variable will contain 35 because * (multiplicative operator) is evaluated before +
(additive operator).

C# Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc.

In C# keywords cannot be used as identifiers. However, if we want to use the keywords as


identifiers, we may prefix the keyword with @ character.

A list of Reserved Keywords available in C# programming language is given below:

<td< td=""></td<>

abstract base as bool break catch

byte char checked class const continue

private protected public return readonly ref

explicit extern false finally fixed float

foreach goto if implicit in in (generic mod

ulong ushort unchecked using unsafe virtual

null object operator out out (generic modifier) override

default delegate do double else enum

sealed short sizeof stackalloc static string

https://E-next.in
switch this throw true try typeof

abstract base as bool break catch

volatile while

Some identifiers which have special meaning in context of code are called as Contextual
Keywords.

A list of Contextual Keywords available in C# programming language is given below:

add group ascending descending dynamic fro

global alias into join let s

partial (type) partial(method) remove orderby

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:

//code to be executed if all cases are not matched;

break;

C# switch statement flow

https://E-next.in
C# Switch Example

using System;

public class SwitchExample

public static void Main(string[] args)

Console.WriteLine("Enter a number:");

int num = Convert.ToInt32(Console.ReadLine());

switch (num)

case 10: Console.WriteLine("It is 10"); break;

case 20: Console.WriteLine("It is 20"); break;

case 30: Console.WriteLine("It is 30"); break;

default: Console.WriteLine("Not 10, 20 or 30"); break;

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:

for(initialization; condition; incr/decr){

//code to be executed

Flowchart:

C# for loop flowchart

C# For Loop Example

using System;

https://E-next.in
public class ForExample

public static void Main(string[] args)

for(int i=1;i<=10;i++){

Console.WriteLine(i);

Output:

10

C# Nested For Loop

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.

Let's see a simple example of nested for loop in C#.

using System;

public class ForExample

public static void Main(string[] args)

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

C# Infinite For Loop

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;

public class ForExample

public static void Main(string[] args)

for (; ;)

Console.WriteLine("Infinitive For Loop");

Output:

Infinitive For Loop

Infinitive For Loop

Infinitive For Loop

Infinitive For Loop

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:

C# While Loop Example


Let's see a simple example of while loop to print table of 1.

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:

C# break statement flowchart

C# Break Statement Example

Let's see a simple example of C# break statement which is used inside the loop.

using System;

public class BreakExample

https://E-next.in
public static void Main(string[] args)

for (int i = 1; i <= 10; i++)

if (i == 5)

break;

Console.WriteLine(i);

Output:

C# Break Statement with Inner Loop

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;

public class BreakExample

public static void Main(string[] args)

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;

C# Continue Statement Example

using System;

public class ContinueExample

public static void Main(string[] args)

for(int i=1;i<=10;i++){

if(i==5){

continue;

Console.WriteLine(i);

Output:

https://E-next.in
1

10

C# Continue Statement with Inner Loop

C# Continue Statement continues inner loop only if you use continue statement inside the inner loop.

using System;

public class ContinueExample

public static void Main(string[] args)

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.

C# Goto Statement Example


Let's see the simple example of goto statement in C#.

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:

You are not eligible to vote!


Enter your age:
11
You are not eligible to vote!
Enter your age:
5
You are not eligible to vote!
Enter your age:
26
You are eligible to vote!

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.

There are two types of comments in C#.

https://E-next.in
Single Line comment

Multi Line comment

C# Single Line Comment

The single line comment starts with // (double slash). Let's see an example of single line comment in C#.

using System;

public class CommentExample

public static void Main(string[] args)

int x = 10;//Here, x is a variable

Console.WriteLine(x);

Output:

10

C# Multi Line Comment

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;

public class CommentExample

public static void Main(string[] args)

/* Let's declare and

print variable in C#. */

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

o Easy to traverse data

o Easy to manipulate data

o Easy to sort data etc.

Disadvantages of C# Array
o Fixed size

C# Array Types
There are 3 types of arrays in C# programming:

1. Single Dimensional Array

2. Multidimensional Array

3. Jagged Array

C# Single Dimensional Array


To create single dimensional array, you need to use square brackets [] after the type.

1. int[] arr = new int[5];//creating array

You cannot place square brackets after the identifier.

1. int arr[] = new int[5];//compile time error

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. int[,] arr=new int[3,3];//declaration of 2D array


2. int[,,] arr=new int[3,3,3];//declaration of 3D array

C# Multidimensional Array Example


Let's see a simple example of multidimensional array in C# which declares, initializes and
traverse two dimensional array.

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.

Declaration of Jagged array

Let's see an example to declare jagged array that has two elements.

int[][] arr = new int[2][];

Initialization of Jagged array

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];

arr[1] = new int[6];

Initialization and filling elements in Jagged array

Let's see an example to initialize and fill elements in jagged array.

arr[0] = new int[4] { 11, 21, 56, 78 };

arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };

Here, size of elements in jagged array is optional. So, you can write above code as given below:

arr[0] = new int[] { 11, 21, 56, 78 };

arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };

C# Jagged Array Example

Let's see a simple example of jagged array in C# which declares, initializes and traverse jagged arrays.

public class JaggedArrayTest

public static void Main()

int[][] arr = new int[2][];// Declare the array

https://E-next.in
arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array

arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };

// Traverse array elements

for (int i = 0; i < arr.Length; i++)

for (int j = 0; j < arr[i].Length; j++)

System.Console.Write(arr[i][j]+" ");

System.Console.WriteLine();

Output:

11 21 56 78

42 61 37 41 59 63

Initialization of Jagged array upon Declaration

Let's see an example to initialize the jagged array while declaration.

int[][] arr = new int[3][]{

new int[] { 11, 21, 56, 78 },

new int[] { 2, 5, 6, 7, 98, 5 },

https://E-next.in
new int[] { 2, 5 }

};

C# Jagged Array Example 2

Let's see a simple example of jagged array which initializes the jagged arrays upon declaration.

public class JaggedArrayTest

public static void Main()

int[][] arr = new int[3][]{

new int[] { 11, 21, 56, 78 },

new int[] { 2, 5, 6, 7, 98, 5 },

new int[] { 2, 5 }

};

// Traverse array elements

for (int i = 0; i < arr.Length; i++)

for (int j = 0; j < arr[i].Length; j++)

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

C# Object and Class

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 a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be accessed through object.

Let's see an example to create object using new keyword.

Student s1 = new Student();//creating an object of Student

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 C# class that has two fields only.

public class Student

int id;//field or data member

String name;//field or data member

C# Object and Class Example

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;

public class Student

int id;//data member (also instance variable)

String name;//data member(also instance variable)

https://E-next.in
public static void Main(string[] args)

Student s1 = new Student();//creating an object of Student

s1.id = 101;

s1.name = "Sonoo Jaiswal";

Console.WriteLine(s1.id);

Console.WriteLine(s1.name);

Output:

101

Sonoo Jaiswal

C# Class Example 2: Having Main() in another class

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;

public class Student

public int id;

public String name;

https://E-next.in
class TestStudent{

public static void Main(string[] args)

Student s1 = new Student();

s1.id = 101;

s1.name = "Sonoo Jaiswal";

Console.WriteLine(s1.id);

Console.WriteLine(s1.name);

Output:

101

Sonoo Jaiswal

C# Class Example 3: Initialize and Display data through method

Let's see another example of C# class where we are initializing and displaying object through method.

using System;

public class Student

public int id;

public String name;

public void insert(int i, String n)

https://E-next.in
{

id = i;

name = n;

public void display()

Console.WriteLine(id + " " + name);

class TestStudent{

public static void Main(string[] args)

Student s1 = new Student();

Student s2 = new Student();

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;

public class Employee

public int id;

public String name;

public float salary;

public void insert(int i, String n,float s)

id = i;

name = n;

salary = s;

public void display()

Console.WriteLine(id + " " + name+" "+salary);

class TestEmployee{

public static void Main(string[] args)

Employee e1 = new Employee();

Employee e2 = new Employee();

e1.insert(101, "Sonoo",890000f);

https://E-next.in
e2.insert(102, "Mahesh", 490000f);

e1.display();

e2.display();

Output:

101 Sonoo 890000

102 Mahesh 490000

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.

There can be two types of constructors in C#.

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 class Employee

public Employee()

Console.WriteLine("Default Constructor Invoked");

public static void Main(string[] args)

Employee e1 = new Employee();

Employee e2 = new Employee();

Output:

Default Constructor Invoked

Default Constructor Invoked

C# Default Constructor Example: Having Main() in another class

Let's see another example of default constructor where we are having Main() method in another class.

https://E-next.in
using System;

public class Employee

public Employee()

Console.WriteLine("Default Constructor Invoked");

class TestEmployee{

public static void Main(string[] args)

Employee e1 = new Employee();

Employee e2 = new Employee();

Output:

Default Constructor Invoked

Default Constructor Invoked

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

public int id;

public String name;

public float salary;

public Employee(int i, String n,float s)

id = i;

name = n;

salary = s;

public void display()

Console.WriteLine(id + " " + name+" "+salary);

class TestEmployee{

public static void Main(string[] args)

Employee e1 = new Employee(101, "Sonoo", 890000f);

Employee e2 = new Employee(102, "Mahesh", 490000f);

e1.display();

e2.display();

https://E-next.in
}

Output:

101 Sonoo 890000

102 Mahesh 490000

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.

Note: C# destructor cannot have parameters. Moreover, modifiers can't be applied on


destructors.

C# Constructor and Destructor Example


Let's see an example of constructor and destructor in C# which is called 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.

o It can be used to pass current object as a parameter to another method.

o It can be used to declare indexers.

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:

101 Sonoo 890000


102 Mahesh 490000

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.

Note: Indexers and destructors cannot be static.

Advantage of C# static keyword


Memory efficient: Now we don't need to create instance for accessing the static members,
so it saves memory. Moreover, it belongs to the type, so it will not get memory each time
when instance is created.

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.

C# static field example


Let's see the simple example of static field in C#.

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:

101 Sonoo 8.8


102 Mahesh 8.8

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.

Points to remember for C# static class


o C# static class contains only static members.

o C# static class cannot be instantiated.

o C# static class is sealed.

o C# static class cannot contain instance constructors.

C# static class example


Let's see the example of static class that contains static field and static method.

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:

Value of PI is: 3.14


Cube of 3 is: 27

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.

Points to remember for C# Static Constructor


o C# static constructor cannot have any modifier or parameter.

o C# static constructor is invoked implicitly. It can't be called explicitly.

C# Static Constructor example


Let's see the example of static constructor which initializes the static field rateOfInterest in
Account class.

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:

101 Sonoo 9.5


102 Mahesh 9.5

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;

public struct Rectangle

public int width, height;

public class TestStructs

https://E-next.in
public static void Main()

Rectangle r = new Rectangle();

r.width = 4;

r.height = 5;

Console.WriteLine("Area of Rectangle is: " + (r.width * r.height));

Output:

Area of Rectangle is: 20

C# Struct Example: Using Constructor and Method

Let's see another example of struct where we are using constructor to initialize data and method to
calculate area of rectangle.

using System;

public struct Rectangle

public int width, height;

public Rectangle(int w, int h)

width = w;

https://E-next.in
height = h;

public void areaOfRectangle() {

Console.WriteLine("Area of Rectangle is: "+(width*height)); }

public class TestStructs

public static void Main()

Rectangle r = new Rectangle(5, 6);

r.areaOfRectangle();

Output:

Area of Rectangle is: 30

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

enum improves type safety

enum can be traversed

C# Enum Example

Let's see a simple example of C# enum.

using System;

public class EnumExample

public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void Main()

int x = (int)Season.WINTER;

int y = (int)Season.SUMMER;

Console.WriteLine("WINTER = {0}", x);

Console.WriteLine("SUMMER = {0}", y);

Output:

WINTER = 0

SUMMER = 2

https://E-next.in
C# enum example changing start index

using System;

public class EnumExample

public enum Season { WINTER=10, SPRING, SUMMER, FALL }

public static void Main()

int x = (int)Season.WINTER;

int y = (int)Season.SUMMER;

Console.WriteLine("WINTER = {0}", x);

Console.WriteLine("SUMMER = {0}", y);

Output:

WINTER = 10

SUMMER = 12

C# enum example for Days

using System;

public class EnumExample

https://E-next.in
{

public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

public static void Main()

int x = (int)Days.Sun;

int y = (int)Days.Mon;

int z = (int)Days.Sat;

Console.WriteLine("Sun = {0}", x);

Console.WriteLine("Mon = {0}", y);

Console.WriteLine("Sat = {0}", z);

Output:

Sun = 0

Mon = 1

Sat = 6

C# enum example: traversing all values using getNames()

using System;

public class EnumExample

public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

https://E-next.in
public static void Main()

foreach (string s in Enum.GetNames(typeof(Days)))

Console.WriteLine(s);

Output:

Sun

Mon

Tue

Wed

Thu

Fri

Sat

C# enum example: traversing all values using getValues()

using System;

public class EnumExample

public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

public static void Main()

https://E-next.in
{

foreach (Days d in Enum.GetValues(typeof(Days)))

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 can have logic while setting values in the C# Properties.

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;

public class Employee

private string name;

public string Name

get

return name;

set

name = value;

class TestEmployee{

public static void Main(string[] args)

https://E-next.in
Employee e1 = new Employee();

e1.Name = "Sonoo Jaiswal";

Console.WriteLine("Employee Name: " + e1.Name);

Output:

Employee Name: Sonoo Jaiswal

C# Properties Example 2: having logic while setting value

using System;

public class Employee

private string name;

public string Name

get

return name;

set

https://E-next.in
{

name = value+" JavaTpoint";

class TestEmployee{

public static void Main(string[] args)

Employee e1 = new Employee();

e1.Name = "Sonoo";

Console.WriteLine("Employee Name: " + e1.Name);

Output:

Employee Name: Sonoo JavaTpoint

C# Properties Example 3: read-only property

using System;

public class Employee

private static int counter;

public Employee()

https://E-next.in
{

counter++;

public static int Counter

get

return counter;

class TestEmployee{

public static void Main(string[] args)

Employee e1 = new Employee();

Employee e2 = new Employee();

Employee e3 = new Employee();

//e1.Counter = 10;//Compile Time Error: Can't set value

Console.WriteLine("No. of Employees: " + Employee.Counter);

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.

C# Single Level Inheritance Example: Inheriting Fields

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;

public class Employee

public float salary = 40000;

public class Programmer: Employee

https://E-next.in
public float bonus = 10000;

class TestInheritance{

public static void Main(string[] args)

Programmer p1 = new Programmer();

Console.WriteLine("Salary: " + p1.salary);

Console.WriteLine("Bonus: " + p1.bonus);

Output:

Salary: 40000

Bonus: 10000

In the above example, Employee is the base class and Programmer is the derived class.

C# Single Level Inheritance Example: Inheriting Methods

Let's see another example of inheritance in C# which inherits methods only.

using System;

https://E-next.in
public class Animal

public void eat() { Console.WriteLine("Eating..."); }

public class Dog: Animal

public void bark() { Console.WriteLine("Barking..."); }

class TestInheritance2{

public static void Main(string[] args)

Dog d1 = new Dog();

d1.eat();

d1.bark();

Output:

Eating...

Barking...

C# Multi Level Inheritance Example

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;

public class Animal

public void eat() { Console.WriteLine("Eating..."); }

public class Dog: Animal

public void bark() { Console.WriteLine("Barking..."); }

public class BabyDog : Dog

public void weep() { Console.WriteLine("Weeping..."); }

class TestInheritance2{

public static void Main(string[] args)

BabyDog d1 = new BabyDog();

d1.eat();

d1.bark();

d1.weep();

Output:

https://E-next.in
Eating...

Barking...

Weeping...

Note: Multiple inheritance is not supported in C# through class.

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.

C# Method Overriding Example


Let's see a simple example of method overriding in C#. In this example, we are overriding
the eat() method by the help of override keyword.

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.

C# base keyword: accessing base class field

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;

public class Animal{

public string color = "white";

public class Dog: Animal

https://E-next.in
{

string color = "black";

public void showColor()

Console.WriteLine(base.color);

Console.WriteLine(color);

public class TestBase

public static void Main()

Dog d = new Dog();

d.showColor();

Output:

white

black

C# base keyword example: calling base class method

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;

public class Animal{

public virtual void eat(){

Console.WriteLine("eating...");

public class Dog: Animal

public override void eat()

base.eat();

Console.WriteLine("eating bread...");

public class TestBase

public static void Main()

Dog d = new Dog();

https://E-next.in
d.eat();

Output:

eating...

eating bread...

C# inheritance: calling base class constructor internally

Whenever you inherit the base class, base class constructor is internally invoked. Let's see the example
of calling base constructor.

using System;

public class Animal{

public Animal(){

Console.WriteLine("animal...");

public class Dog: Animal

public Dog()

Console.WriteLine("dog...");

https://E-next.in
public class TestOverriding

public static void Main()

Dog d = new Dog();

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.

C# Runtime Polymorphism Example

https://E-next.in
Let's see a simple example of runtime polymorphism in C#.

using System;

public class Animal{

public virtual void eat(){

Console.WriteLine("eating...");

public class Dog: Animal

public override void eat()

Console.WriteLine("eating bread...");

public class TestPolymorphism

public static void Main()

Animal a= new Dog();

a.eat();

Output:

https://E-next.in
eating bread...

C# Runtime Polymorphism Example 2

Let's see a another example of runtime polymorphism in C# where we are having two derived classes.

using System;

public class Shape{

public virtual void draw(){

Console.WriteLine("drawing...");

public class Rectangle: Shape

public override void draw()

Console.WriteLine("drawing rectangle...");

public class Circle : Shape

public override void draw()

https://E-next.in
{

Console.WriteLine("drawing circle...");

public class TestPolymorphism

public static void Main()

Shape s;

s = new Shape();

s.draw();

s = new Rectangle();

s.draw();

s = new Circle();

s.draw();

Output:

drawing...

drawing rectangle...

drawing circle...

Runtime Polymorphism with Data Members

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;

public class Animal{

public string color = "white";

public class Dog: Animal

public string color = "black";

public class TestSealed

public static void Main()

Animal d = new Dog();

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.

Note: Structs are implicitly sealed therefore they can't be inherited.

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.

It is used to achieve multiple inheritance which can't be achieved by class. It is used to


achieve fully abstraction because it cannot have method body.

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:

public abstract void draw();

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;

public abstract class Shape

public abstract void draw();

public class Rectangle : Shape

public override void draw()

Console.WriteLine("drawing rectangle...");

public class Circle : Shape

public override void draw()

https://E-next.in
{

Console.WriteLine("drawing circle...");

public class TestAbstract

public static void Main()

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

static void Main(string[] args)

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 {

public class Hello

public void sayHello() { Console.WriteLine("Hello First Namespace"); }

namespace Second

public class Hello

public void sayHello() { Console.WriteLine("Hello Second Namespace"); }

public class TestNamespace

public static void Main()

First.Hello h1 = new First.Hello();

Second.Hello h2 = new Second.Hello();

https://E-next.in
h1.sayHello();

h2.sayHello();

Output:

Hello First Namespace

Hello Second Namespace

C# namespace example: by using keyword

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 {

public class Hello

public void sayHello() { Console.WriteLine("Hello Namespace"); }

namespace Second

public class Welcome

https://E-next.in
{

public void sayWelcome() { Console.WriteLine("Welcome Namespace"); }

public class TestNamespace

public static void Main()

Hello h1 = new Hello();

Welcome w1 = new Welcome();

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

Clone() It is used to return a reference to this instance of String.

Compare(String, String) It is used to compares two specified String objects. It returns an int
their relative position in the sort order.

CompareOrdinal(String, It is used to compare two specified String objects by evaluating the


String) the corresponding Char objects in each string..

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.

Concat(String, String) It is used to concatenate two specified instances of String.

Contains(String) It is used to return a value indicating whether a specified substring


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.

GetHashCode() It returns the hash code for this string.

GetType() It is used to get the Type of the current instance.

GetTypeCode() It is used to return the TypeCode for class String.

IndexOf(String) It is used to report the zero-based index of the first occurrence of t


in this instance.

https://E-next.in
Insert(Int32, String) It is used to return a new string in which a specified string is inse
index position.

Intern(String) It is used to retrieve the system's reference to the specified String.

IsInterned(String) It is used to retrieve a reference to a specified String.

IsNormalized() It is used to indicate that this string is in Unicode normalization form

IsNullOrEmpty(String) It is used to indicate that the specified string is null or an Empty str

IsNullOrWhiteSpace(String) It is used to indicate whether a specified string is null, empty, o


white-space characters.

Join(String, String[]) It is used to concatenate all the elements of a string array, u


separator between each element.

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.

PadLeft(Int32) It is used to return a new string that right-aligns the characters


padding them with spaces on the left.

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

StartsWith(String) It is used to check whether the beginning of this string instance ma


string.

Substring(Int32) It is used to retrieve a substring from this instance. The substring s


character position and continues to the end of the string.

ToCharArray() It is used to copy the characters in this instance to a Unicode charac

ToLower() It is used to convert String into lowercase.

ToLowerInvariant() It is used to return convert String into lowercase using the casing ru
culture.

ToString() It is used to return instance of String.

ToUpper() It is used to convert String into uppercase.

Trim() It is used to remove all leading and trailing white-space character


String object.

TrimEnd(Char[]) It Is used to remove all trailing occurrences of a set of characters sp


from the current String object.

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

System.DivideByZeroException handles the error generated by dividing a number with zero.

System.NullReferenceException handles the error generated by referencing the null object.

System.InvalidCastException handles the error generated by invalid typecasting.

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.

C# Exception Handling Keywords

In C#, we use 4 keywords to perform exception handling:

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.

C# example without try/catch

using System;

public class ExExample

https://E-next.in
public static void Main(string[] args)

int a = 10;

int b = 0;

int x = a/b;

Console.WriteLine("Rest of the code");

Output:

Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.

C# try/catch example

using System;

public class ExExample

public static void Main(string[] args)

try

int a = 10;

int b = 0;

int x = a / b;

https://E-next.in
}

catch (Exception e) { Console.WriteLine(e); }

Console.WriteLine("Rest of the code");

Output:

System.DivideByZeroException: Attempted to divide by zero.

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.

C# finally example if exception is handled

using System;

public class ExExample

public static void Main(string[] args)

try

int a = 10;

int b = 0;

https://E-next.in
int x = a / b;

catch (Exception e) { Console.WriteLine(e); }

finally { Console.WriteLine("Finally block is executed"); }

Console.WriteLine("Rest of the code");

Output:

System.DivideByZeroException: Attempted to divide by zero.

Finally block is executed

Rest of the code

C# finally example if exception is not handled

using System;

public class ExExample

public static void Main(string[] args)

try

int a = 10;

int b = 0;

https://E-next.in
int x = a / b;

catch (NullReferenceException e) { Console.WriteLine(e); }

finally { Console.WriteLine("Finally block is executed"); }

Console.WriteLine("Rest of the code");

Output:

Unhandled Exception: System.DivideBy

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

search object, and

sort object

In sort, all the data structure work can be performed by C# collections.

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 classes (Now deprecated)

System.Collections.Concurrent classes

1) System.Collections.Generic classes

The System.Collections.Generic namespace has following 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.

It is like SortedDictionary<TKey, TValue> class.

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.

C# SortedList<TKey, TValue> example


Let's see an example of generic SortedList<TKey, TValue> class that stores elements using
Add() method and iterates elements using for-each loop. Here, we are using KeyValuePair
class to get key and value.

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.

2. We can have logic while setting values in the C# Properties.

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:

Employee Name: Sonoo Jaiswal

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.

The best use of delegate is to use as event.

Internally a delegate declaration defines a class which is the derived class


of System.Delegate.

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:

After c1 delegate, Number is: 120


After c2 delegate, Number is: 360

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.

For example, consider a delegate:

public delegate int MyDelegate (string s);

The preceding delegate can be used to reference any method that has a
single string parameter and returns an int type variable.

Syntax for delegate declaration is:

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:

public delegate void printString(string s);


...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);

Following example demonstrates declaration, instantiation, and use of a


delegate that can be used to reference methods that take an integer
parameter and returns an integer value.

using System;

delegate int NumberChanger(int n);


namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}

public static int MultNum(int q)


{
num *= q;

https://E-next.in
return num;
}
public static int getNum()
{
return num;
}

static void Main(string[] args)


{
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);

//calling the methods using the delegate objects


nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(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: 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;

delegate int NumberChanger(int n);


namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}

public static int MultNum(int q)


{
num *= q;
return num;
}

public static int getNum()


{
return num;
}

static void Main(string[] args)


{
//create delegate instances
NumberChanger nc;

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);

// this method prints to the console


public static void WriteToScreen(string str)
{
Console.WriteLine("The String is: {0}", str);
}

//this method prints to a file


public static void WriteToFile(string s)
{
fs = new FileStream("c:\\message.txt",
FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}

// this method takes the delegate as parameter and uses it to


// call the methods as required
public static void sendString(printString ps)
{
ps("Hello World");
}
static void Main(string[] args)
{
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);

https://E-next.in
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:

The String is: Hello World

.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:

Components and their Description

(1) Common Language Runtime or CLR

It performs memory management, exception handling, debugging, security


checking, thread execution, code execution, code safety, verification, and
compilation. The code that is directly managed by the CLR is called the managed
code. When the managed code is compiled, the compiler converts the source code
into a CPU independent intermediate language (IL) code. A Just In Time(JIT)
compiler compiles the IL code into native code, which is CPU specific.

(2) .Net Framework Class Library

It contains a huge library of reusable types. classes, interfaces, structures, and


enumerated values, which are collectively called types.

(3) Common Language Specification

It contains the specifications for the .Net supported languages and


implementation of language integration.

(4) Common Type System

It provides guidelines for declaring, using, and managing types at runtime, and
cross-language communication.

(5) Metadata and Assemblies

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.

(6) Windows Forms

Windows Forms contain the graphical representation of any window displayed in


the application.

(7) ASP.NET and ASP.NET AJAX

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.

(9) Windows Workflow Foundation (WF)

It helps in building workflow-based applications in Windows. It contains activities,


workflow runtime, workflow designer, and a rules engine.

(10) Windows Presentation Foundation

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 is the technology used for building and executing connected systems.

(12) Windows CardSpace

It provides safety for accessing resources and sharing personal information on the
internet.

(13) LINQ

It imparts data querying capabilities to .Net languages using a syntax which is


similar to the tradition query language SQL.

Net Framework is a platform that provides tools and technologies to develop Windows, Web
and Enterprise applications. It mainly contains two components,

1. Common Language Runtime (CLR)

2. .Net Framework Class Library.

1. Common Language Runtime (CLR)

.Net Framework provides runtime environment called Common Language


Runtime (CLR).It provides an environment to run all the .Net Programs. The code which
runs under the CLR is called as Managed Code. Programmers need not to worry on
managing the memory if the programs are running under the CLR as it provides memory
management and thread management.

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.

2. .Net Framework Class Library (FCL)

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.

4. XML Web Services.

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.

3. Common Type System (CTS)

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.

4. Common Language Specification (CLS)

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.

Common language specification Rules:

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:

1. Representation of text strings

2. Internal representation of enumerations

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.

Below mentioned the .Net Architecture stack for easy understanding.

https://E-next.in

S-ar putea să vă placă și