C# Slide Teacher

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 166

C# TUTORIAL

Teacher: Sanaullah sediqe 0771009709


.NET FRAMEWORK
 .NET is a framework which is used to develop software applications. It is designed and
developed by Microsoft and first beta version released on 2000.
 It is used to build applications for web, Windows, phone and provides broad range of
functionalities and support for industry standards.
 This framework contains large number of class libraries known as Framework Class Library
(FCL).
 The software programs written in .NET are execute in execution environment that is called
CLR (Common Language Runtime).
 This Framework provides various services like: memory management, networking, security
and memory safety. It also supports numerous programing languages like: C#, F#, VB etc.
COMPONENTS OF THE .NET FRAMEWORK
.NET COMPILATION PROCESS
 Compilation process Done By Two Phase
 First Phase is Done by language compiler
 Second Phase of Compilation is Done By JIT(just in Time)
WHAT IS C#

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


provided by Microsoft that runs on .NET Framework.
 C# is a simple & powerful object-oriented programming language developed by
Microsoft. C# can be used to create various types of applications, such as web,
windows, console applications or other types of applications using Visual studio.
 By the help of C# programming language, we can develop different types of secured
and robust applications:
C# HISTORY
 History of C# language is interesting to know. Here we are going to discuss brief history of
C# language.
 C# has evolved much since its first release in 2002. C# was introduced with .NET Framework
1.0 and the current version of C# is 6.0 .
 Anders Hejlsberg is known as the founder of C# language.
 It is based on C++ and Java
C# FEATURES
 C# is object oriented programming language. It provides a lot of features that are given below.
 Simple
 Modern programming language
 Object oriented
 Scalable and Updateable
 Rich Library
 Fast speed
C# IDE
 For C# we use Different IDE but The Most Popular IDE Is Visual Studio
 Steps For First Time Writing of Program in C#
 Open visual studio go to file menu click on new click on project
 Select The Template of C# and Write The Name of The Program
 Click On OK Button.
STRUCTURE OF C# PROGRAM
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
RULES FOR DEFINING VARIABLES

 A variable can have alphabets, digits and underscore.


 A variable name can start with alphabet and underscore only. It can't start with digit.
 No white space is allowed within variable name.
 A variable name must not be any reserved word or keyword e.g. char, float etc
 Valid variable names:
 int x;
 int _x;
 int k20
 Invalid variable names: c books?
C# DATA TYPES
A data type specifies the type of data that a variable can store such as integer, floating,
character etc.
C# DATA TYPES
There are 3 types of data types in C# language .

Types Data Types

Value Data Type short, int, char, float, double etc

Reference Data Type String, Class, Object and Interface

Pointer Data Type Pointers


VALUE DATA TYPE
 The value data types are integer-based and floating-point based. C# language
supports both signed and unsigned literals.
There are 2 types of value data type in C# language.
 1) Predefined Data Types - such as Integer, Boolean, Float, etc.
 2) User defined Data Types - such as Structure, Enumerations, etc.
 The memory size of data types may change according to 32 or 64 bit operating
system.
Data Types Memory Size Range

char 1 byte -128 to 127


signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 127


short 2 byte -32,768 to 32,767
signed short 2 byte -32,768 to 32,767
unsigned short 2 byte 0 to 65,535
int 4 byte -2,147,483,648 to -2,147,483,647

signed int 4 byte -2,147,483,648 to -2,147,483,647

unsigned int 4 byte 0 to 4,294,967,295


long 8 byte ?9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

signed long 8 byte ?9,223,372,036,854,775,808 to


9,223,372,036,854,775,807
unsigned long 8 byte 0 - 18,446,744,073,709,551,615

float 4 byte 1.5 * 10-45 - 3.4 * 1038, 7-digit


precision
double 8 byte 5.0 * 10-324 - 1.7 * 10308, 15-digit
precision

decimal 16 byte at least -7.9 * 10?28 - 7.9 * 1028, with


at least 28-digit precision
REFERENCE DATA TYPE
 The reference data types do not contain the actual data stored in a variable, but
they contain a reference to the variables.
 If the data is changed by one of the variables, the other variable automatically
reflects this change in value.
 There are 2 types of reference data type in C# language.
 1) Predefined Types - such as Objects, String.
 2) User defined Types - such as Classes, Interface.
REFERENCE TYPE
POINTER DATA TYPE
 The pointer in C# language is a variable, it is also known as locator or indicator that points to
an address of a value.

Symbols used in pointer

Symbol Name Description

& (ampersand sign) Address operator Determine the address of


a variable.
* (asterisk sign) Indirection operator Access the value of an
address.
DECLARING A POINTER

 The pointer in C# language can be declared using * (asterisk symbol).


 int * a; //pointer to int
 char * c; //pointer to char
POINTS TO REMEMBER
 Value type stores the value in its memory space, whereas reference type stores the address of the
value where it is stored.
 Primitive data types and struct are of the 'Value' type. Class objects, string, array, delegates are
reference types.
 Value type passes by value by default. Reference type passes by reference by default.
 Value types and reference types stored in Stack and Heap in the memory depends on the scope of
the variable.
C# CLASS
 class is like a blueprint of specific object. In the real world, every object has some color, shape
and functionalities. For example, the luxury car Ferrari. Ferrari is an object of the luxury car
type
 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
 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

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

 class: is a keyword which is used to define class.


 Program: is the class name. A class is a blueprint or template from which objects are created.
It can have data members and methods. Here, it has only Main method.
 static: is a keyword which means object is not required to access static members. So it saves
memory.
 void: is the return type of the method. It does't return any value. In such case, return statement
is not required.
 Main: is the method name. It is the entry point for any C# program. Whenever we run the C#
program, Main() method is invoked first before any other method. It represents start up of the
program.
 string[] args: is used for command line arguments in C#. While running the C# program, we
can pass values. These values are known as arguments which we can use in the program.
 System.Console.WriteLine("Hello World!"): Here, System is the namespace. Console is the
class defined in System namespace. The WriteLine() is the static method of Console class
C# BASIC INPUT AND OUTPUT

 System.Console.Write();// it is used for print a massage


 System.Console.WriteLine();// it is use for print a massage with new line
 The above Two Method are use for printing Message on Console
 Console.ReadLine();// Read number of character from keyboard it Return string
 Console. Read(); single return type int
 System.Console.RedKey();
EXAMPLE
 using System;
 public class Student
 {
 int id;//data member (also instance variable)
 String name;//data member(also instance variable)

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

 }
 }
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:
 Simple Example
 Using System
 Using public modifier
 Using namespace
EXAMPLE
 using System;
 class Program
 {
 static void Main(string[] args)
 {
 Console.WriteLine("Hello World!");
 }
 }
C# OPERATORS
 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.
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Unary Operators
 Ternary Operators
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:
 int data= 10+ 5*5 .
 The "data" variable will contain 35 because * (multiplicative operator) is evaluated before +
(additive operator).
int result;
int x = 10, y = 5;

// Addition
result = (x + y);
Console.WriteLine("Addition Operator: " + result);

// Subtraction
result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);

// Multiplication
result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result);

// Division
result = (x / y);
Console.WriteLine("Division Operator: " + result);

// Modulo
result = (x % y);
Console.WriteLine("Modulo Operator: " + result);
EXAMPLE
 class Program
 {
 static void Main(string[] args)
 {

 int firstNumber = 5, secondNumber = 10, result;


 result = firstNumber + secondNumber;
 Console.WriteLine("{0} + {1} = {2}", firstNumber, secondNumber, result);

 Console.ReadKey();

 }
 }
 Console.WriteLine("Value = {0}", val);

{0} is the placeholder for variable val which will be replaced by value of val. Since only one variable is used so there is only
one placeholder
EXAMPLE
 class Program {

static void Main(string[] args) {


bool a = true; bool b = true;
if (a && b) {
Console.WriteLine("Line 1 - Condition is true"); }
if (a || b) { Console.WriteLine("Line 2 - Condition is true");
}
/* lets change the value of a and b */ a = false; b = true;
if (a && b) { Console.WriteLine("Line 3 - Condition is true"); }
else { Console.WriteLine("Line 3 - Condition is not true"); }
if (!(a && b)) { Console.WriteLine("Line 4 - Condition is true"); }
Console.ReadLine(); } }}
END CHAPTER #1
CONTROL
STATEMENT
Teacher: Sanaullah sediqe 0771009709
C# IF-ELSE

 In C# programming, the if statement is used to test the condition. There are various types of if
statements in C#.
 if statement
 if-else statement
 nested if statement
 if-else-if ladder
C# IF STATEMENT
 The C# if statement tests the condition. It is executed if condition is true
 The if statement is single selection control structure.
 Syntax:
 if(condition){
 //code to be executed
}
EXAMPLE
 using System;
 public class IfExample
 {
 public static void Main(string[] args)
 {
 int num = 10;
 if (num % 2 == 0)
 {
 Console.WriteLine("It is even number");
 }
 } }
C# IF-ELSE STATEMENT
 The C# if-else statement also tests the condition. It executes the if block if condition is true

 otherwise else block is executed.


 Syntax:

 if(condition){

 //code if condition is true

 }else{ //code if condition is false }


 Example:

 using System;

 public class IfExample

 {
 public static void Main(string[] args) {
 int num = 11;
 if (num % 2 == 0)
 {
 Console.WriteLine("It is even number"); }
 else
 { Console.WriteLine("It is odd number"); } } }
C# IF-ELSE EXAMPLE: WITH INPUT FROM

USER
using System;
 public class IfExample
 {
 public static void Main(string[] args)
 {
 Console.WriteLine("Enter a number:");
 int num = Convert.ToInt32(Console.ReadLine());
 if (num % 2 == 0)
 {
 Console.WriteLine("It is even number");
 }
 else
 {
 Console.WriteLine("It is odd number");
 } }
 } Convert.ToInt32() converts a value to a 32-bit signed integer (int) data type.
C# IF-ELSE-IF STATEMENT
 The C# if-else-if ladder statement executes one condition from multiple statements
 Syntax:
 if(condition1){
 //code to be executed if condition1 is true
 }else if(condition2){
 //code to be executed if condition2 is true
 }
 else if(condition3){
 //code to be executed if condition3 is true
 }
 ...
 else{
 //code to be executed if all the conditions are false
C# IF ELSE-IF EXAMPLE
 using System;
 public class IfExample
 {
 public static void Main(string[] args)
 {
 Console.WriteLine("Enter a number to check grade:");
 int num = Convert.ToInt32(Console.ReadLine());
 if (num <0 || num >100)
 {
 Console.WriteLine("wrong number");
 }
 else if(num >= 0 && num < 50){
 Console.WriteLine("Fail");
 }
 else if (num >= 50 && num < 60)
 {
 Console.WriteLine("D Grade");
 else if (num >= 60 && num < 70)
 {
 Console.WriteLine("C Grade");
 }
 else if (num >= 70 && num < 80)
 {
 Console.WriteLine("B Grade");
 }
 else if (num >= 80 && num < 90)
 {
 Console.WriteLine("A Grade");
 }
 else if (num >= 90 && num <= 100)
 {
 Console.WriteLine("A+ Grade");
 }
 }
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 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;
 }
 }
C# SWITCH EXAMPLE
 char ch;
 Console.WriteLine("Enter an alphabet");
 ch = Convert.ToChar(Console.ReadLine());
 switch(Char.ToLower(ch))
 {
 case 'a':
 case 'e':
 case 'i':
 case 'o':
 case 'u':
 Console.WriteLine("Vowel");
 break;
 default:
 Console.WriteLine("Not a vowel");
 break; }
LOOP IN C#
 Looping in a programming language is a way to execute a
statement or a set of statements multiple numbers of times
depending on the result of a condition to be evaluated. The
resulting condition should be true to execute statements within
loops.
 In C# We have Three Type Of Loop
 For Loop(Foreach Loop is one of The Type For Loop)
 While Loop
 Do While Loop
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
}
C# FOR LOOP EXAMPLE
 using System;
 public class ForExample
 {
 public static void Main(string[] args)
 {
 for(int i=1;i<=10;i++){
 Console.WriteLine(i);
 }
 }
 }
SUM OF NUMBERS FROM 1-10
 int sum = 0;
 for(int i=0;i<100;i++)
 {
 Console.WriteLine("" + i);
 sum = i + sum;
 }
 Console.WriteLine("the sum+" + sum);
C# NESTED FOR LOOP
 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.
 Example:
 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);
 }
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");
 }
 }
 }
FOR EACH LOOP IN C#
 The foreach statement in C# iterates through a collection of items such as an array or list, The
foreach body must be enclosed in {} braces unless it consists of a single statement.
 Foreach loop (or for each loop) is a control flow statement for traversing items in a
collection
 foreach loop is used to iterate over the elements of the collection. The collection may be an
array or a list. It executes for each element present in the array.
 Syntax:

foreach(data_type var_name in collection_variable) {


// statements to be executed
}
FLOWCHART OF FOREACH LOOP

•It is necessary to enclose the statements of foreach loop in curly braces {}.
•Instead of declaring and initializing a loop counter variable, you declare a
variable that is the same type as the base type of the array, followed by a
colon, which is then followed by the array name.
•In the loop body, you can use the loop variable you created rather than using
an indexed array element.
EXAMPLES
 1- class Program
 {
 static void Main(string[] args)
 {
 Console.WriteLine("foreach loop Sample!");
 int[] oddArray = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 };
 foreach (int num in oddArray)
 {
 Console.WriteLine(num);
 }
 Console.ReadKey();
 }
 }
EXAMPLES
-Use foreach to find a char in a string

 string name = “C# programming";


 // Convert string into an array of chars
 char[] chArray = name.ToCharArray();

 // Loop through chars and display one char at a time
 foreach (char ch in chArray)
 {
 if (ch.ToString() != " ")
 Console.WriteLine(ch);
 }
EXAMPLE
 -Foreach in Collection
 // Find number of occurrences of a char in a string
 string str = "A monkey stole a banana";
 char[] chars = str.ToCharArray();
 int ncount = 0;
 // Loop through chars and find all 'n' and count them
 foreach (char ch in chars)
 {
 if (ch == 'n')
 ncount++;
 }
 Console.WriteLine($"Total n found {ncount}");
EXAMPLE
 int[] number_array = new int[5];
 for (int i = 0; i < number_array.Length; i++)
 {
 Console.WriteLine("Enter value #" + (i + 1) + ": ");
 number_array[i] = Convert.ToInt32(Console.ReadLine());
 }
 Console.WriteLine("Numbers entered:");
 foreach (int number in number_array)
 {
 Console.WriteLine(number);
 }

 Console.ReadKey();
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:
 while(condition){
 //code to be executed
}
C# WHILE LOOP EXAMPLE
 using System;
 public class WhileExample
 {
 public static void Main(string[] args)
 {
 int i=1;
 while(i<=10)
 {
 Console.WriteLine(i);
 i++;
 }
 }
 }
C# NESTED WHILE LOOP
EXAMPLE:
 In C#, we can use while loop inside another while loop, it is known as nested while loop. The nested
while loop is executed fully when outer loop is executed once.
 using System;

 public class WhileExample {

 public static void Main(string[] args) {


 int i=1;
 while(i<=3) {
 int j = 1;
 while (j <= 3) { Console.WriteLine(i+" "+j);
 j++;
 }
 i++; }
 } }
C# INFINITIVE WHILE LOOP
EXAMPLE:
 We can also create infinite while loop by passing true as the test condition.
 using System;
 public class WhileExample
 {
 public static void Main(string[] args)
 {
 while(true)
 {
 Console.WriteLine("Infinitive While Loop");
 }
 }
 }
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:
 do{
 //code to be executed
 }while(condition);
C# DO-WHILE LOOP EXAMPLE
 using System;
 public class DoWhileExample
 {
 public static void Main(string[] args)
 {
 int i = 1;
 do{
 Console.WriteLine(i);
 i++;
 } while (i <= 10) ;
 }
 }
C# NESTED DO-WHILE LOOP
 In C#, if you use do-while loop inside another do-while loop, it is known as nested do-while loop. The nested do-while loop is
executed fully for each outer do-while loop.
 using System;
 public class DoWhileExample
 {
 public static void Main(string[] args)
 {
 int i=1;
 do{
 int j = 1;
 do{
 Console.WriteLine(i+" "+j);
 j++;
 } while (j <= 3) ;
 i++;
 } while (i <= 3) ;
C# INFINITIVE DO-WHILE
LOOP EXAMPLE
 using System;
 public class WhileExample
 {
 public static void Main(string[] args)
 {

 do{
 Console.WriteLine("Infinitive do-while Loop");
 } while(true);
 }
 }
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;
C# BREAK STATEMENT
EXAMPLE
 using System;
 public class BreakExample
 {
 public static void Main(string[] args)
 {
 for (int i = 1; i <= 10; i++)
 {
 if (i == 5)
 {
 break;
 }
 Console.WriteLine(i);
 }
 }
 }
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);
 }
 }
 }
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# GO TO STATEMENT EXAMPLE
 using System;
 public class GotoExample
 {
 public static void Main(string[] args)
 {
 ineligible:
 Console.WriteLine("You are not eligible to vote!");
 Console.WriteLine("Enter your age:\n");
 int age = Convert.ToInt32(Console.ReadLine());
 if (age < 18){
 goto ineligible;
 }
 else
 {
 Console.WriteLine("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#.


 Single Line comment //
 Multi Line comment /* */
END OF CHAPTER 02
C# FUNCTION

 Function is a block of code that has a signature. Function is used to execute statements
specified in the code block. A function consists of the following components:
 C# Function Syntax
 <access-specifier><return-type>FunctionName(<parameters>)
{
 // function body
 // return statement
}
 Access-specifier, parameters and return statement are optional.
TYPE OF FUNCTION
 User defined functions

A type of function written by programmer is known as user defined function.


 Built-in functions

A type of function that is available as a part of language is known as built-in function or


library function . These functions are ready made programs and these functions are stored in
different header files .built-in function make program easer and faster to write.
C# FUNCTION

 Function name: It is a unique name that is used to make Function call.


 Return type: It is used to specify the data type of function return value.
 Body: It is a block that contains executable statements.
 Access specifier: It is used to specify function accessibility in the application.
 Parameters: It is a list of arguments that we can pass to the function during call.
USER DEFINED FUNCTION
 A user defined function consists of the following
 Function declaration and Definition
 Function Call
EXAMPLE OF FUNCTION
 Create show function
 Create calculate function
 Create function to Return a value
ARRAY IN C#
 Array is collection of homogenous data elements stored and accessed by single name.
 An array is a group of contiguous memory location that all have the same name and
type.
 When we want to store multiple values in one variable so we use array.
 Simple variable is a single memory location with a unique name and type but An array
is a collection of different adjacent memory locations.
 All these memory locations have one collective name and type .
 Each element In array is accessed with reference to its position of location in the array.
 the position is called index or subscript.
RULES FOR ARRAYS

 The array should be declared with same data type.

 The size of the arrays should be specified at the time of its declaration.

 In an array, elements are stored sequentially, that is, in contiguous memory locations.

 Only one element can be added or removed from the array at a time
ADVANTAGE OF ARRAY
 Arrays can store a large number of values with single name.

 Arrays are used to process many values easily and quickly.

 The values stored in an array can be sorted easily.

 A search process can be applied on arrays easily.


TYPES OF ARRAY
 Arrays can be broadly classified into two types:
 One dimensional arrays
 Multi-dimensional arrays

 A one-dimensional array has only one subscript and a multi-dimensional array has n
subscripts, n presents the dimensions of the array.
 Multi-dimensional arrays can be further classified into two dimensional and three-dimensional
arrays.
 The dimensionality of an array is determined by the number of pairs of square brackets placed
after the array name.
 One dimensional array array1[ ], two dimensional array2[ ,]three dimensional array
array3[ ,,].
ONE-DIMENSIONAL ARRAY
 A type of array in which all elements are arranged in the form of a list is known as
one dimensional array.
 Its also called single dimensional array or linear list
 In one-dimensional array the data is stored in a sequence of memory locations.
 Each individual element in an array can be referred by subscripted variables and its
declared form is as
Where:
 data-type is any valid data type i.e. int, float, char etc.
 array-name is the name of array
 size indicates the number of locations in which data elements are to be stored

Note: Size of array must be positive integer.


string[] Books = new string[5];

EXAMPLE
 For example, if the marks of ten students are to be processed in a program we might use
an array to store them.
 The computer must be instructed to reserve a sequence of ten memory locations for
storing the marks, the array can be defined or declared for this purpose as :
string[] Books = new string[5];

This statement reserves ten locations in memory for storing elements


 Here string specifies the type of elements or items that will be stored in the array.
 The word Books is the name of array.
 [5] indicates the number of locations or the number of variables of type int in which data
 elements are to be stored which all should be integer type.

 It will look like in memory as


EXAMPLE
 //Declaring single dimensional array
 string[] Books = new string[5];
 Books[0] = "C#";
 Books[1] = "Java";
 Books[2] = "VB.NET";
 Books[3] = "C++";
 Books[4] = "C";
 Console.WriteLine("All the element of Books array is:\n\n");
 int i = 0;
 //Formatting Output
 Console.Write("\t1\t2\t3\t4\t5\n\n\t");
 for (i = 0; i < 5; i++)
 {
 Console.Write("{0}\t", Books[i]);
 }
 Console.ReadLine();
EXAMPLE
 // declares a 1D Array of string.
 string[] weekDays;

 // allocating memory for days.
 weekDays = new string[] {"Sun", "Mon", "Tue", "Wed",
 "Thu", "Fri", "Sat"};

 // Displaying Elements of array
 foreach(string day in weekDays)
 Console.Write(day + " ");
EXAMPLE
 Console.WriteLine("Enter Size for Array !");
 int size = Convert.ToInt32(Console.ReadLine());//Declaration and Initialization of array
 int[] arr = new int[size];
 //traversing array
 for (int i = 0; i <size; i++)
 {
 Console.WriteLine(i);

 }
 Console.ReadKey();
EXAMPLE
 Console.WriteLine("Enter value for Array !");
 int size = Convert.ToInt32(Console.ReadLine());//Declaration and Initialization of array
 int[] arr = new int[size];

 //traversing array
 for (int i = 0; i <size; i++)
 {
 Console.WriteLine(“The index number {0}:”,i);
 arr[i]=convert.toInt32(Console.RedLine());
 }
 Console.ReadKey();
DISPLAY VLAUE
 Foreach(int k in arr)
{

Console.writeLine(k);
sum+=k
}
Consol.writeLine(“The sum is =”+sum);
TWO-DIMENSIONAL ARRAY
 Two dimensional array can be considered as a table that consists of rows and
columns .
 Each element in 2-d array is referred with the help of two indexes.
 One index is used to indicate the row and the second index indicates the column
of the element.
Data_type [Row,Cols] identifier;
 Identifier indicate the name of array
 Rows indicates the number of rows in the array.
 Cols indicates the number of columns in the array.

Int [,]arr;
 This example shows an array with 4 rows and 3 columns
DECLARING AND &
INITIALIZING 2D ARRAY
 Similar to a 1D array, the elements 2D array can be initialized either one at a time or all at
once.
 Syntax
 int[,] arr=new int[3,3];//declaration of 2D array
 int[,] arr=new int[3,3];//declaration of 2D array
 arr[0,1]=10;//initialization
 arr[1,2]=20;
 arr[2,0]=30;
 int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
EXAMPLE
 int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//declaration and initialization

 //traversal
 for(int i=0;i<3;i++){
 for(int j=0;j<3;j++){
 Console.WriteLine(“ The value:”+arr[i,j]+" ");
 }

EXAMPEL
 Console.WriteLine("Enter The Array Row Size !");
 int Rowsize = Convert.ToInt32(Console.ReadLine());
 Console.WriteLine("Enter The Arrary Column Size !");
 int Columnsize = Convert.ToInt32(Console.ReadLine());
 int[,] numbers = new int[Rowsize,Columnsize];
 int sum = 0;
 for (int i = 0; i < Rowsize; i++)
 {
 for (int j = 0; j < Columnsize; j++)
 {
 numbers[i, j] = Convert.ToInt32(Console.ReadLine());
 sum = sum + numbers[i,j];
 }
 }
CONT.…
 Console.WriteLine("the sum is =" + sum);
 Console.WriteLine(" The value is called !");
 foreach (int value in numbers)
 {
 Console.WriteLine(value + "");
 }
 Console.ReadKey();
 }
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
 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
 public class Student
 {
 int id;//data member (also instance variable)
 String name;//data member(also instance variable)
 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);
 }
 }
HAVING MAIN() IN ANOTHER CLASS
 using System;
 public class Student
 {
 public int id;
 public String name;
 }
 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);
 }
 }
INITIALIZE AND DISPLAY DATA THROUGH METHOD

 public class Student


 {
 public int id;
 public String name;
 public void insert(int i, String n)
 {
 id = i;
 name = n;
 }
 public void display()
 {
 Console.WriteLine(id + " " + name);
 }
 }
CONT.…
 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();
 }
 }
CONSTRUCTOR IN C#
 A special method of the class that is automatically invoked when an instance of the class is
created is called a constructor.
 The main use of constructors is to initialize the fields of the class while creating an instance for
the class.
 When you have not created a constructor in the class, the compiler will automatically create
a default constructor of the class. The default constructor initializes all numeric fields in the class
to zero and all string and object fields to null.
 It is like a Method but it has not Return Type.
 A single class can have multiple constructors means we can have more than one constructor in a
class. It is also called as overloaded constructor
 A benefit of using a constructor is that it guarantees that the object will go through a proper
initialization before an object being used means we can pre-initialize some of the class variables
with values before an object being used.
TYPE OF CONSTRUCTOR
 Default Constructor
 Parameterized Constructor
DEFAULT CONSTRUCTOR
 constructor which has no argument is known as default constructor. It is invoked at the time of creating
object.
 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();
 }
 }
C# PARAMETERIZED
CONSTRUCTOR
 A constructor which has parameters is called parameterized constructor. It is used to provide differe
 using System;
 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;
 }
CONT.…
 public void display()
 {
 Console.WriteLine(id + " " + name+" "+salary);
 }
 }
 class TestEmployee{
 public static void Main(string[] args)
 {
 Employee e1 = new Employee(101, “ahmad", 890000f);
 Employee e2 = new Employee(102, “Mansoor", 490000f);
 e1.display();
 e2.display();
 }
 }
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
 In c#, Destructor is a special method of a class, and it is used in a class to destroy the object or instances of classes
 using System;
 public class Employee
 {
 public Employee()
 {
 Console.WriteLine("Constructor Invoked");
 }
 ~Employee()
 {
 Console.WriteLine("Destructor Invoked");
 }
 }
CONT..
 class TestEmployee{
 public static void Main(string[] args)
 {
 Employee e1 = new Employee();
 Employee e2 = new Employee();
 }
 }
C# ACCESS MODIFIERS / SPECIFIERS

 C# Access modifiers or specifiers are the keywords that are used to specify accessibility or scope
of variables and functions,Clasess in the C# application.
 C# provides five types of access specifiers.
 Public: It specifies that access is not restricted.
 Protected: It specifies that access is limited to the containing class or in derived class.
 Private: It specifies that access is limited to the containing type
C# THIS

 In C# programming, this is a keyword that refers to the current instance of the class. There can main
usage of this keyword in C#.

 The “this” keyword in C# is used to refer to the current instance of the class. It is also used to
differentiate between the method parameters and class fields if they both have the same name.
 Another usage of “this” keyword is to call another constructor from a constructor in the same class
CONT..
 using System;
 public class Employee
 {
 public int id;
 public String name;
 public float salary;
 public Employee(int id, String name,float salary)
 {
 this.id = id;
 this.name = name;
 this.salary = salary;
 }
 public void display()
 {
 Console.WriteLine(id + " " + name+" "+salary); }}
CONT.…
 class TestEmployee{
 public static void Main(string[] args)
 {
 Employee e1 = new Employee(101, “ahmad", 890000af);
 Employee e2 = new Employee(102, “ajmal", 490000af);
 e1.display();
 e2.display();

 }
 }
C# STATIC

 In C#, static means something which cannot be instantiated. You cannot create an object of a static
class and cannot access static members using an object.

 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, class .
 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.
STATIC CLASS
 Static Class can not be initialized , it means you can not use the new keyword to
Create a variable of Class type .
 Static Class can not inherit from any Class except ,System.obj.
 Example of Static Class is in C# System.Math.
 All the member of static class must be static otherwise the compiler throw the error.
EXAMPLE
 public static class Calculator
 { private static int _resultStorage = 0;//it is a class level Variable.
 public static string Type = "Arithmetic";
 public static int Sum(int num1, int num2)
 {
 return num1 + num2; }
 public static void Store(int result)
 { _resultStorage = result;
 }
}
CONT.…
 Above, the Calculator class is a static. All the members of it are also static.
 You cannot create an object of the static class; therefore the members of the static class can be
accessed directly using a class name like ClassName.MemberName, as shown below.
 class Program
 {
 static void Main(string[] args)
{
 var result = Calculator.Sum(10, 25); // calling static method
 Calculator.Store(result);
 var calcType = Calculator.Type; // accessing static variable
 Calculator.Type = "Scientific"; // assign value to static variable
 }
 }
C# NAMESPACES
 Namespaces in C# are used to organize too many classes so that it can be easy to handle the
application.

 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 that we don't have to use complete name all the time.
INTRODUCTION TO INHERITANCE IN C#

 Inheritance in C# is the process of acquiring all the properties of one class into another class.
 There are two classes referred to as base class and derived class. The base class is also
known as parent class and the properties or methods of this class we want to inherit to another
class.
 The derived class is known as child class that is used to inherit the properties and methods of
the base class or parent class. It helps in reusing the same code again and no need to define the
same properties again and again.
 Inheritance is one of the powerful concepts or fundamental attributes of
object-oriented programming language. It is widely used in all the OOPs based programming
language. Its main purpose is to use the same code again. The example of the Basic Structure
of Inheritance is given below:
CONT.…
 Derived Class (child) - the class that inherits from another class
 Base Class (parent) - the class being inherited from
 To inherit from a class, use the : symbol.
 class BaseClass { }
class ChildClass: BaseClass {}
 Types of Inheritance in C#

There are different types of Inheritance in C#:


1. Single Level Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
ADVANTAGES OF INHERITANCE IN C#

 It helps in using the same code again means code reusability.


 It reduces code redundancy.
 It helps in reading the code more comfortably.
 It also reduces the size of the source code and file.
 It helps in dividing the large code into small pieces.
 Private members are not accessed in derived class when base class members are inherited by
the derived class
 Polymorphism is the other oops concept that can be achieved with the help of Inheritance only.
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 Name=“Ahmad”;
 { public float salary = 40000; }
 public class Programmer: Employee
 { 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);
 } }
EXAMPLE
 class Animal{
 void eat(){System.out.println("eating...");}
 }
 class Dog : Animal{
 void bark(){System.out.println("barking...");}
 }
 class TestInheritance{
 public static void main(String args[]){
 Dog d=new Dog();
 d.bark();
 d.eat();
 }}
MULTILEVEL 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
 class Animal{
 void eat(){Console.Writline ("eating...");}
 }
 class Cat: Animal{
 void bark(){Console.Writline (“running...");}
 }
 class BabyCat : Cat{
 void weep(){Console.Writline ("weeping...");}
 } class TestInheritance2{ public static void main(String args[]){
 BabyCat d=new BabyDog();
 d.weep();
 d.bark();

MULTIPLE INHERITANCE
EXAMPLE
 C# does not support multiple inheritances of classes. To
overcome this problem we can use interfaces, we will see more
about interfaces in my next article in detail
EXAMPLE
 class Human{
 void eat(){Console.Writline(“ Human can eating...");
 Void
 }
 }
 Class boy : Human{
 void run(){Console.Writline(“ boy can running...");}
 }
 class Baby: Human,boy{
 void walk(){Console.Writline (“child can not waking...");}
 } class TestInheritance2{ public static void main(String args[]){
 Baby d=new Baby();
 d.eat();
 d.run();
 d.walk(); }}
HIERARCHICAL INHERITANCE EXAMPLE

 This is the type of inheritance in which there are


multiple classes derived from one base class. This
type of inheritance is used when there is a
requirement of one class feature that is needed in
multiple
EXAMPLE
 class A //base class
 { public string msg()
 {
 return "this is A class Method"; }
 }
 class B : A
 { public string info()
 { msg();
 return "this is B class Method"; }
 class C : A
 {
 public string getinfo()
 {
 msg();
 return "this is C class Method"; } } }
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#

1-compile time polymorphism


Compile time polymorphism is achieved by method overloading in C#. It is also known as
static binding or early binding.
2- runtime polymorphism.
Runtime polymorphism in achieved by method overriding which is also known as dynamic
binding or late binding.
METHOD OVERLOADING
 Having two or more methods with same name but different in parameters, is known as method
overloading in C#.
 The advantage of method overloading is that it increases the readability of the program because
you don't need to use different names for same action.
 You can perform method overloading in C# by two ways:

1-By changing number of arguments


2-By changing data type of the arguments
CONT.…
 using System;

 public class Calculator{

 public static int add(int a,int b){


 return a + b;
 }
 public static int add(int a, int b, int c)
 {
 return a + b + c;
 } }
 public class TestMemberOverloading

 {

 public static void Main()


 {
 Console.WriteLine(Cal.add(12, 23));
 Console.WriteLine(Cal.add(12, 23, 25));
 } }
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.
CONT.…
 using System;
 public class Animal{
 public virtual void eat(){
 Console.WriteLine("Eating...");
 }
}
 public class Dog: Animal
{
 public override void eat()
 {
 Console.WriteLine("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.
EXAMPLE
 public string color = "white";
 using System;
 public class Animal{
 }
 public class Dog: Animal
 {
 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(); } }
CALLING BASE CLASS METHOD
 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();
 d.eat(); } }
DIFFERENCE BETWEEN OVERLOADING
AND OVERRIDING
 In Overloading we Define multiple methods with the same name by changing their parameter
 In Overriding we Define multiple methods with the same name and same parameter
 Overloading is perform within the class as well as between parent and Child class
 Overriding is perform between parent and child class only.
 While overloading a parent classes method under the child class, child class dose not
required any permission from the parent class, child class required a permission from it is
parent class
 While overriding a parent class method under child class
ABSTRACTION IN C#
 abstraction is a process of hiding the implementation details and showing only
functionality to the user.
 Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know
the internal processing about the message delivery.
 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.
 A normal class cannot have abstract methods. An abstract class is a class that contains at
least one abstract method. We can understand the concept by the shape
 Abstraction can be achieved by two ways:

1-Abstract class(0-100%)
2-Interface(100%)
 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:
 Syntax:
 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
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.
EXAMPLE
 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()
 {
 Console.WriteLine("drawing circle..."); } }
CONT.…
 public class TestAbstract
 {
 public static void Main()
 {
 Shape s;
 s = new Rectangle();
 s.draw();
 s = new Circle();
 s.draw();
 }
 }
C# INTERFACE

 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 The class which implements the interface,
must provide the implementation of all the methods declared inside the interface.
 Note: Interface methods are public and abstract by default. You cannot explicitly use
public and abstract keywords for an interface method
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.
 using System;
 public interface Drawable
 {
 void draw();
 }
 public class Rectangle : Drawable
 {
 public void draw()
 {
 Console.WriteLine("drawing rectangle...");
 }
 }
CONT..
 public class Circle : Drawable
 {
 public void draw()
 {
 Console.WriteLine("drawing circle...");
 } }
 public class TestInterface
 {
 public static void Main()
 {
 Drawable d;
 d = new Rectangle();
 d.draw();
 d = new Circle();
 d.draw(); } }
CONT.…
 Note: Interface methods are public and abstract by default. You cannot explicitly use public
and abstract keywords for an interface method
 using System;
 public interface Drawable
{
 public abstract void draw();//Compile Time Error
}
MULTIPLE INHERITANCE BY
INTERFACE
 public interface Interface1
 {
 void Test();
 void Show();
 }
 public interface Interface2
 {
 void Test();
 void Show();
 }
 class ImplementInterafce : Interface1, Interface2
 {
 public void Test()
 {
 Console.WriteLine("Test method is implemented");
 }
 public void Show()
 {
 Console.WriteLine("Show mwthod is implemented");
 }
 class Program

 {

 static void Main(string[] args)

 {

 ImplementInterafce obj = new ImplementInterafce();

 obj.Test();

 obj.Show();

 Interface1 obj1 = new ImplementInterafce();

 obj1.Test();

 obj1.Show();

 Interface2 obj2 = new ImplementInterafce();

 obj2.Test();

 obj2.Show();

 Console.WriteLine("Press any key to exist.");

 Console.ReadKey();

 }

 }

 }
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, comparison, 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.
 string s1 = "hello";//creating string using string keyword
 String s2 = "welcome";//creating string using String class
EXAMPLE
 using System;
 public class StringExample
 {
 public static void Main(string[] args)
 {
 string s1 = "hello";

 char[] ch = { 'c', 's', 'h', 'a', 'r', 'p' };
 string s2 = new string(ch);

 Console.WriteLine(s1);
 Console.WriteLine(s2);
 }
 }
C# STRING METHODS

 Split(char[])
 ToLower()
 ToUppwer()
 ToString()
 Replace()
 Remove()
 join(string,string[])
 lastIndexof(char)
SPLIT()
 public static void Main(string[] args)
 {
 string s1 = "Hello C Sharp";
 string[] s2 = s1.Split(' ');
 foreach (string s3 in s2)
 {
 Console.WriteLine(s3);
 }
TO STRING()
 public static void Main(string[] args)
 {
 string s1 = "Hello C#";
 int a = 123;
 string s2 = s1.ToString();
 string s3 = a.ToString();
 Console.WriteLine(s2);
 Console.WriteLine(s3);
 }
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

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.
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
 throw
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
 public static void Main(string[] args)
 {
 int a = 10;
 int b = 0;
 int x = a/b; ///
 Console.WriteLine("Rest of the code");
 }
 Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero
CONT…
 public static void Main(string[] args)
 {
 try
 {
 int a = 10;
 int b = 0;
 int x = a / b;
 }
 catch (Exception e) { Console.WriteLine(e); }

 Console.WriteLine("Rest of the code");
 }
 System.DivideByZeroException: Attempted to divide by zero. Rest of the code
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
 public static void Main(string[] args)
 {
 try
 {
 int a = 10;
 int b = 0;
 int x = a / b;
 }
 catch (Exception e) { Console.WriteLine(e); }
 finally { Console.WriteLine("Finally block is executed"); }
 Console.WriteLine("Rest of the code");
 System.DivideByZeroException: Attempted to divide by zero. Finally block is executed Rest of the code
EXAMPLE
 try
 {
 int arr[]= {1,3,5,7};
 Consol.WriteLine (arr[10]); //may throw exception
 }
 // handling the array exception
 catch(System.IndexOutOfRangeException e)
 {
 Console.WrietLine(e);
 }
 Console.WrietLine ("rest of the code");
THROW KEYWORD
 In c#, the throw is a keyword and it is useful to throw an exception manually
during the execution of the program and we can handle those thrown exceptions
using try-catch blocks based on our requirements. The throw keyword will raise
only the exceptions that are derived from the Exception base class.
 throw exception;
 public static void fn(Int32 age)
{
if (age < 0)
{
// throw an argument out of range exception if the age is
// less than zero.
throw new ArgumentOutOfRangeException("Age Cannot Be Negative ");
}
}

public static void Main()


{
try
{
fn(-10);
}

catch (Exception e)
{
Console.WriteLine(String.Concat(e.StackTrace, e.Message));
Console.ReadLine();
}
END

You might also like