Vous êtes sur la page 1sur 98

Introduction to C#

What is C#?

Language Created by Anders Hejlsberg (father of Delphi)


Developed by Microsoft
Developed specifically for .NET
Principle Influencing Languages:
C++
Delphi
Java
Designed to be an optimal Windows development language

What C# coding Looks Like:


using System;
namespace Test
{
class ExampleClass
{
static void Main()
{
System.Console.WriteLine(Program");
}
}

Characteristics

Object-oriented.
Primarily imperative or procedural.
Structured (as opposed to monolithic).
Strongly typed.
ISO and ECMA standardized.

Why C#?
The first Component Oriented language in the C/C++ family
C# is pure object-oriented, compared to C++ which is a mixture of object-oriented and procedure-oriented.

Everything really is an object


Next generation robust and durable software
Event-driven, fully OO, visual programming language
Has IDE

Ease-to-development, The rich class library makes many functions easy to be implemented
You need not put much attention on such problems as memory leak, which is troubling problem for C++ programmer
Good support for distributed system

Note: Process of rapidly creating an application using an IDE is called Rapid Application Development (RAD)

Where and When to use C#?


C# is pretty much the language for developing business applications targeting a Windows environment, and it's a leading Web language,
as well as gaining ground in game programming and extending to Mobile development
Need For:

Modernized language
Cross-language and Cross-platform capabilities
Versioning to provide ease of administration and deployment.
Migration from C/C++ and Java easily
Interoperate with other languages
XML support for Web-based component interaction

C# also gives you the capability to build durable system-level components by virtue of the following features:

Full COM/Platform support for existing code integration.


Robustness through garbage collection and type safety.
Security provided through intrinsic code trust mechanisms.
Full support of extensible metadata concepts.

Types of Application

Console
Application
Has standard
streams (out, in, err)

GUI can be added


manually

Windows
Application

Service

GUI based

No standard streams
(out, in, err)

No standard streams
(out, in, err)

Main thread is
commandeered by
the SCM

Main thread is shared


by the GUI message
pump & your code

No GUI

IDE

MS Visual Studio
A fully-featured, and extensible IDE for creating modern applications for Windows, Android, and iOS, as well as web applications and
cloud services
Microsoft Integrate Development Environment (IDE)
Create, run, and debug programs
Visual Programming
Create program by dragging and dropping predefined building blocks into place
Languages Supported
C#, Visual Basic, F#, C++, HTML, JavaScript, Python, and more
Microsoft Visual Studio Products
Visual Studio Community (Free for developers - Create multi-platform apps for Windows, iOS, Android)
Visual Studio Professional
Visual Studio Enterprise (Complete Edition)
Visual Studio Code (Code editing for building and debugging modern web and cloud applications
Visual Studio Team Services (Share code, track work, and ship software)
Team Foundation Server
Available in
Chinese, English, French, Portuguese, German, Italian, Japanese, Korean, Spanish and Russian
Note: MSDN stands for Microsoft Developer Network
7

Versions of VS, C# and .net framework


Version

Date

.NET Framework

Visual Studio

C# 1.0

January 2002

.NET Framework 1.0

Visual Studio .NET 2002

C# 1.2

April 2003

.NET Framework 1.1

Visual Studio .NET 2003

C# 2.0

November 2005

.NET Framework 2.0

Visual Studio 2005

C# 3.0

November 2007

.NET Framework 2.0 (Except LINQ/Query


Extensions)
.NET Framework 3.0 (Except LINQ/Query
Extensions)
.NET Framework 3.5

Visual Studio 2008


Visual Studio 2010

C# 4.0

April 2010

.NET Framework 4

Visual Studio 2010

C# 5.0

August 2012

.NET Framework 4.5

Visual Studio 2012


Visual Studio 2013

C# 6.0

July 2015

.NET Framework 4.6

Visual Studio 2015

Members - 1

Example showing Variables declaration and


initialization

Variables
Members in c#, are the members in class that represents
data and behavior of the class. Variable is one such member
in class.

Variable is name given to storage location to store data.


Each variable has specific data type that determines which
kind of data to be stored in variable.
Syntax
Variable declaration

datatype variable_name;
Ex: int i;
i is variable of the type int.
Variable initialization
1. datatype variable_name=value;
Ex: int i=100;
i is variable of the type int and stores value of 100.
2. variable_name=value;
Ex: i=100;

10

Constants

Example showing constant declaration and usage

Constant is one of member in class.


It refers to fixed value that cannot be altered by the
program during the execution.
These fixed values are also called as literals.
Constants can be any c# built in data type like integer,
float, character and string.
Const keyword is used to declare constants.
Syntax
Const data_type Constant_name;
Ex: const string name=John;
name is declared as constant of the type string
and it is assigned with the value as John .
This value can not be changed by the program
during the execution.

11

Properties

Example showing property declaration and usage

Properties are extension of fields(i.e. member variables and


methods) and are accessed using same syntax.

Provides flexible mechanism to read, write or compute the


value of a private field using accessors.
Properties uses get and set accessors to read and write the
private fields.
The value keyword is used to define the value being
assigned by the set accessor.
Property can have get accessor, set accessor or both the
accessor
Property that do not implement set accessor are read only.
Syntax
data_type Property_name
{
get; set;
}
FirstName is declared as property of the type string.
Get and set accessor used to read and write the private variable called
name.
12

Members - 2

Methods
Method is a group of statements put together to perform a
task.

Example showing method declaration and usage

To use method , need to declare a method and call method


has to be performed.

Syntax
Access_specifier Return_type Method_name(parameterlist)
{
//statements to execute.
}
Access_specifier: determines the visibility of the
method.
Return_type: A method may return value. Return type
is the data type of the value that method returns. If
the method is not returning any value then return
type is void.
Method_name: it is unique identifier.
Parameterlist: it is enclosed in paranthesis, these
values are used to pass and receive data from the
method.
Statement to execute: set of the statements to be
executed to complete the specific tasks.

14

Constructor

Example of constructor

Constructor is special method of class which will invoke


automatically whenever instance of the class is created.
Constructor are responsible for object initialization and memory
allocation to its class.
Constructor name should be same as class name.
Parameters can be passed to a contractor. Constructor without
parameters is called as default constructor.
Contractors will not have return type.

Syntax
Access_specifier constructor_name(parameterlist)
{
//code for initialzation.
}

Here PersoalDetails is class with constructor as PersonalDetails(). It is


initializing the name with the default value as John

15

Destructor

Example of Destructor

Destructor are used to destruct instance of class.


A class can have only one destructor.
Destructors can not be called. They are invoked
automatically.
Destructors does not have parameters.
Destructor name is same as class name with negation
symbol.
Syntax
~ destructor_name()
{
//code for clean up.
}

16

Boxing, Unboxing and Type conversions

Data type
Data Types in a programming language describes that what type of data a variable can hold.
Since C# is type-safe language, every variable and object must have a declared type.
Each data type needs some specific size of memory to hold that particular data.
There are two types of data types

Value types
Reference types

Value type: It stores the copy of the value.


Reference type: It stores the address of the value.

18

Boxing and unboxing


Converting a value type to reference type is called Boxing.
Converting a reference type to value type is called unboxing.
A boxing conversion permits any value-type to be implicitly converted to the type object.
An unboxing conversion permits an explicit conversion from type object to any value-type.
In boxing process, a value type is being allocated on the heap rather than the stack.
In unboxing process, boxed value type is unboxed from the heap and assigned to a value type which is being allocated on the stack.

19

Implicit and explicit type conversion


Type conversion is converting one type of data to another type which is also known as typecasting.
There are two types in type casting
Implicit typecasting: conversions from smaller to larger integral types and conversions from derived classes to base classes
Explicit typecasting: These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast
operator. Also, C# provides following build-in conversion methods.

Example of implicit and explicit conversion is,

20

Operators - 1

Operators
An operator is a symbol that tells the complier to perform specific mathematical or logical manipulation in an expression.
Operators in programming languages are taken from mathematics. These are used to process the data in an expression.
C# provides rich set of built in operators, below are the few operators provided by c#.

Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Operator Precedence

22

Arithmetic Operators

Below table represents all the arithmetic operators supported in C#. And example respectively.
Consider integer variable A is assigned with value of 60 and integer variable B is assigned with value of 30.
Example represents usage of arithmetic operators. AddNumbers() method is performing addition on operands A and B.
Other operators can be used similarly as in the example to perform various mathematic manipulations.

23

Relational Operators
Below table represents all the relational operators supported in C#. And example respectively.
Consider integer variable A is assigned with value of 10 and integer variable B is assigned with value of 30.
Example represents usage of relational operators. FindLargestNumber() method is used find largest number among operands
A and B.
Other operators can be used similarly as in the example to perform various mathematic manipulations.

24

Logical Operators
Below table represents all the logical operators supported in C#. And example respectively.
Consider Boolean variable A is assigned with value of true "and boolean variable B is assigned with value of false.
Example represents usage of logical operators. VerifyUsernameAndPassword() method is used verify the user credentials.
Other operators can be used similarly as in the example to perform various mathematic manipulations.

25

Operators - 2

Bitwise Operators
Below table represents all the bitwise operators supported in C#. And example respectively.
These operators works on bits and perform bit by bit operation.
Consider int variable A is assigned with value of 60 and int variable B is assigned with value of 13.

27

Assignment Operators
Below table represents all the assignment operators supported in C#. And example respectively.

28

Below example shows usage of assignment operator

In the example below simple = assign operator is used. It assigns value from right hand side operands to left hand side
operand.
Here value of A+B that is 90 is assigned to variable result.

29

Operator Precedence
Operator precedence defines the grouping of terms in an expression.
Certain operators have higher precedence than others.
For example, the multiplication operator has higher precedence than the addition operator.
x = 10+ 2* 2;
In the expression above 2*2 will be performed 1st as multiplication operator has higher precedence than addition.
The value of 2*2=4 will be added to 10. So the result will be 14.
Below table represents the common C# operators ordered by precedence (highest precedence first):

30

Operator Precedence continued


In the table above we can see column called Associativity. The associativity of operators determines the order of evaluation
of operators with the same precedence level.
For Example,
Consider expression: X= 10 / 2 * 2;
In the above expression division and multiplication are with the same precedence. In this case associativity rule is
considered to manipulate the expression.
The multiplication, division and modulo operator are left to right associated. So the expression is evaluated this way:
(10 / 2) * 2 and the result is 10.

31

Decision Making and Branching - 1

if statement
If statement consist of a Boolean value followed by
one or more statements.

Start

Syntax and Example:


If(condition)
{
//executes if ture
}

Condition
true

false

If block

End

33

If else statement consist of a Boolean value. If it is true executes if


block of code else executes else block of code.

If else statement
Start

Syntax and Example:


If(condition)
{ //executes if true}
Else
{//executes if false}

Condition
true

false

If block

Else block

End

34

Nested If statement
Start

false

Condition
true
true
Condition

To handle complex conditions nested if statements are used. We can


use, one if or else if statements inside another if or else if
statements.
Syntax and Example:
If(condition)
{
if(condition){//If block code}
else {//Else block code}
}

false

true

Else Block

If block

End

End
35

Decision Making and Branching - 2

Else If ladder statement consist of a Boolean value, if condition is true


if block of code get executes and rest of the ladder will be bypassed.
Otherwise it goes on checking for else if condition till statement gets
true or get ends.
Syntax and example:
If(condition)
{
//executes if ture
}
Else if(condition)
{}
Else{}

Else if ladder statement


Start

Condition
false

true

If block
true

Else if Condition
false
true
If block

Else block

End

37

Switch Statement
Switch statement contains one or more case labels which are
tested against switch condition.

Switch
Condition

If any of the case matches then corresponding code block will


get executes.

Case 1 Block

If none of the case matches, default code block get executes.

Case 2 Block

This can be used as a replacement for long else if ladder


statements to avoid more execution time.
Nested switch : One switch statement can be used in another
switch statement.

Case 3 Block

Default Block
End
38

Example for Switch Statement:

39

Ternary Operator
This operator is used to make conditional expression in C#.
Syntax:
Condtion?statement1:expression2;
Example:

40

Decision Making and Looping - 1

It runs the block of statements repeatedly.

For loop

This loop appropriate when we know exact number of executions to perform on


code.
Syntax:
for (initializer_list; boolean_expression; iterator_list)
// statements of code
}

Initialization

Example:

Condition
False

Code Block

Increment

End

42

Foreach loop
This iterates over a collection.
This deals with the each element of the collection. It does not iterate with index number.

We should not modify the collection while iterating.

Syntax:
foreach(datatype item in collection)
{
//statement of code
}
Example:

43

Decision Making and Looping - 2

It runs the block of statements repeatedly as long as the condition is true.


While loop

Syntax:
while (condition)
{
// statements of code
}

Example:
Condition
False

Code Block

End

45

It is similar to while except it executes block of code at least once.

Do While loop

For and while check the condition at the beginning of the loop, but it checks the
condition at the end of the loop.
For and while runs the block of code zero or more times but it executes block of code at
least one time.

Code Block

Syntax:
do
{
//statements of code
}
while (condition)

Condition

Example:

False
End

46

Few keyword in loops


Break:
Break keyword is used to exit from the loops mentioned above at any point of the time inside loop block.
Continue:
Continue keyword is used to step to next iteration in the loop. Using continue keyword will not executes the statements
following continue keyword inside the loop block.
Example:

47

Encapsulations using Access Specifiers

Encapsulations using Access Specifiers


Encapsulation is process of hiding irrelevant information from end user.
Implemented by using access specifiers.
Access specifiers defines scope of class members.
Below table represents different types of access specifiers and visibility level.

49

Syntax and example


public access specifier : Member can be accessed by any code in assembly and from any other assembly references it

50

private access specifier : Member can only be accessed by code in the same class

51

protected access specifier : Member can only be accessed by code in the same class or in a derived class.

52

internal access specifier : Member can be accessed by any code in the same assembly, but not from another assembly.

53

protected internal access specifier : Member can be accessed by any code in the same assembly, or by any derived class
in another assembly.

54

Types in C# - 1

Class
The class is the fundamental building block of code and it is like blueprint which specifies what a type can do.
It is example for encapsulation in C#
We define class using keyword class
Syntax to define a class
Access_specifier class class_name

Default access specifier for the class is internal


Example of defining class
public class Country
{ }

56

Example of Class

57

Object

Object will be instantiated to use the class members in the code.


Objects can be created by using the new keyword followed by the name of the class.

Object creates a memory for the class and allows us to use the members of the class.
Syntax to define a object
Object_type object_name;

Syntax to instantiate an object


Object_type object_name = new Object_type ();
Ex: Country usa = new Country();

58

Object Declaration and using class members

59

Types in C# - 2

interface
It is same like a class but has no implementation.

It has only definition of properties, methods and events.


Interfaces are inherited by classes.
We define interface using keyword interface
Syntax to define an interface
Access_specifier interface interface_name
Default access specifier for the members of an interface is public
Example of defining class
public interface ICountry
{ }

61

Example of an Interface

62

Enum

The enum keyword is used to declare an enumeration.


An enumeration is a set of named integer constants.
Syntax to define an enumeration
enum enum_name { enumeration list};
Example of defining enumeration
enum Result
{ }

63

Example of an Enumeration

64

Delegates

A delegate in C# is similar to a function pointer in C or C++.


It is another type in C# that represents references to methods.
Delegates perfectly suited for "anonymous" invocation.
Syntax to define an delegate
Access_specifier delegate return_type delegate_name(parameters if any)
Example of defining delegate
public delegate int FindRank(Enum result);

65

Example of Delegates

66

Arrays

Arrays
Collection of items which are of same data type.
An array index starts at zero.
Declaration of simple array
int[] intArray;
Defining arrays
string[] stringArray = new string[10];
Initializing dynamic array
string[] stringArray = new string[] { India", USA", China", Japan, UK" };
Initializing fixed length array
string[] stringArray = new string[5] { India", USA", China", Japan, UK" };
Accessing arrays
Console.WriteLine(stringArray [0]); Console.WriteLine(stringArray [1]); Console.WriteLine(stringArray [2]);

68

Types of Arrays
There are three types in arrays
Single-dimensional array
Multidimensional array
Jagged array
Single dimensional array:
Single-dimensional arrays are the simplest form of arrays.
Example explained in previous slide is single-dimensional array.
Multidimensional array:
A multi-dimensional array is an array with more than one dimension.
A multi-dimensional array can be fixed-sized or dynamic sized
Declaring a multidimensional array
string[,] mutliDimStringArray

Column 0

Column 1

Row 0

India

Asia

Row 1

China

Asia

Row 2
USA
Initializing multidimensional array
string[,] countryNames = new string[3, 2] { { India", Asia" }, { China", Asia" }, { USA", America" }};

America

Accessing multidimensional arrays


Console.WriteLine(countryNames [0,0]); Console.WriteLine(countryNames [0,1]); Console.WriteLine(countryNames [1,1]);
69

Jagged Arrays
Jagged arrays are arrays of arrays.
The elements of a jagged array are other arrays.
Declaring jagged arrays
string[][] stringJaggedArray = new string[3][];
Initializing jagged array
stringJaggedArray [0] = new string [3] {Asia, Africa, America};
stringJaggedArray [1] = new string [5] {India, South Africa, USA, China, Japan};
stringJaggedArray [2] = new string [7] {New Delhi, Johannesburg, Washington, Beijing, Tokyo};
Accessing jagged array
Console.WriteLine(stringJaggedArray [1][0]);
We can also have multidimensional arrays inside an array.

70

Collections

List
List is same as arrays except there is no fixed size for this.
List is a collection of items which are of same data type.
Syntax for defining a List
List<data type> listName;
Initializing List
List<data type> listName = new List<data type>();
Adding items to the List
listName.Add(item);
Accessing List data
Console.WriteLine(listName [0]);

72

ArrayList
ArrayList is same as List except it can hold the items of any data type.
ArrayList is a collection of items which are of same data type or different data type.
An ArrayList index starts at zero.
Syntax for defining a ArrayList

ArrayList arrayListName;
Initializing ArrayList
ArrayList arrayListName = new ArrayList ();

Adding items to the ArrayList


arrayListName.Add(item);
Accessing ArrayList data
Console.WriteLine(arrayListName [0]);

73

Dictionary
Dictionary is same as List, but it holds the items in the form of key value pair.
Dictionary is a collection of items that in the form of key value pair which are of same data type.
Syntax for defining a Dictionary
Dictionary<type_Key, type_value> dictionaryName;
Initializing Dictionary
Dictionary<type_Key, type_value> dictionaryName = new Dictionary<type_Key, type_value>();
Adding items to the Dictionary
dictionaryName.Add(key, value);
Accessing Dictionary data
Console.WriteLine(dictionaryName [0]);

74

HashTable
Hashtable is same as Dictionary, but it can holds the items in the form of key value pair which are of any data type.
Hashtable is a collection of items that in the form of key value pair which are of same data type or different data type.
Syntax for defining a Hashtable
Hashtable hashtableName;
Initializing Hashtable
HashTable hashtableName = new HashTable();
Adding items to the Hashtable
hashtableName.Add(key, value);
Accessing Hashtable data
Console.WriteLine(hashtableName [0]);

75

Operator Keywords 1

Operator Keywords
Used to perform miscellaneous actions such as creating objects, checking the run-time type of an object, obtaining the size of a type,
and other actions.

Following keywords are available

o
o
o
o
o

as
is
new
sizeof
stackalloc

o
o
o
o

typeof
true
false
await

77

as
as operator casts object to a different type.
It returns null if object was of an incompatible type.
Considers Boxing/Unboxing conversion, reference conversion , but user defined conversion are not considered.

class Base
{
public override string ToString()
{
return "Base Class";
}
}
class Derived : Base { }

class Program
{
static void Main()
{
Derived d = new Derived();
Base b = d as Base;
if (b != null)
Console.WriteLine(b.ToString());
}
}

78

is
The is keyword compares an object to a type, and if they're the same or of the same "kind" (the object inherits the type), returns true
Using is on a null variable always returns false.
Considers Boxing/Unboxing conversion, reference conversion , but user defined conversion are not considered.

Example:

object iObj = 123;


bool b1 = iObj is int;
bool b2 = iObj is string;
Console.WriteLine("n1 is int ? " + b1.ToString());
Console.WriteLine("n1 is string ? " + b2.ToString());

79

New operator
Used to create objects and invoke constructors
If the new operator fails to allocate memory, it throws the exception, OutOfMemoryException.
Syntax : general form
class-name object-name = new class-name();
Example

Derived d = new Derived();


int i = new int();

80

Operator Keywords 2

sizeof
Used to obtain the size in bytes for an unmanaged type.
Unmanaged type include built-in types, enum type, pointer type, user defined structs.

static void Main()


{
Console.WriteLine("The size of short is {0}.", sizeof(short));
Console.WriteLine("The size of int is {0}.", sizeof(int));
Console.WriteLine("The size of long is {0}.", sizeof(long));
}

Expression
sbyte
byte
short
ushort
int
uint
long
ulong
char

value
1
1
2
2
4
4
8
8
2

float
double
decimal
bool

4
8
16
1 82

(Unicode)

typeof
Used to determine the type of the parameter passed to it.
It returns the System. Type object associated with that type

static Type _type = typeof(char); // Store Type as field.

static void Main()


{
Console.WriteLine(_type); // Value type pointer
Console.WriteLine(typeof(int)); // Value type
Console.WriteLine(typeof(byte)); // Value type
Console.WriteLine(typeof(Array)); // Class type
Console.WriteLine(typeof(int[])); // Array reference type
}

83

True/false operator
The true and false operators can be overloaded, to allow a class to represent its own state as true or false.
returns the bool value true to indicate that an operand is true and returns false otherwise.

public class MyClass


{
public MyClass(int x, int y) { }
public static bool operator true(MyClass op)
{
// Evaluation code...
return true;
}
public static bool operator false(MyClass op)
{
// Evaluation code...
return false;
}
}

MyClass test = new MyClass(4, 3);


if (test)
Console.WriteLine("Something true");
else
Console.WriteLine("Something false");

84

stackalloc
The stackalloc keyword is used in an unsafe code context to allocate a block of memory on the stack.
Reason to use stackalloc is performance, faster to allocate memory on heap and automatically freed when method exits.
Example

int* fib = stackalloc int[100];

A block of memory of sufficient size to contain 100 elements of type int is allocated on the stack, not the heap

the address of the block is stored in the pointer fib.

The lifetime of the memory block is limited to the lifetime of the method in which it is defined

85

Stackalloc - Example
static unsafe void Main()
{
const int arraySize = 20;
int* fib = stackalloc int[arraySize];
int* p = fib;
// The sequence begins with 1, 1.
*p++ = *p++ = 1;
for (int i = 2; i < arraySize; ++i, ++p)
{
// Sum the previous two numbers.
*p = p[-1] + p[-2];
}
for (int i = 0; i < arraySize; ++i)
{
Console.WriteLine(fib[i]);
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}

86

Exception Handling

Exception Handling
The C# language's exception handling features help you deal with any unexpected or exceptional situations that occur when a program
is running.

Exceptions provide a way to transfer control from one part of a program to another.

88

Blocks of Exception
C# exception handling is built upon four keywords
o

try: code that could throw an exception is put in the try block

catch: The catch keyword indicates the catching of an exception. exception handling code goes in this block.

finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown.

throw: A program throws an exception when a problem shows up. This is done using a throw keyword.

89

Syntax
try
{
// Statement causing exception
}

catch (Exception ex1)


{
// Error handling code
}

You can list down multiple catch statements to catch


different type of exceptions in case your try block raises
more than one exception in different situations.

catch (Exception ex2)


{
// Error handling code
}

finally
{
// Statements to be executed
}

90

Handling multiple Exceptions


try
{
// Statement causing exception
}

catch (IndexOutOfRangeException ex)

Exception is the most general type of exception.


The rules of exception handling tells us that we should
always use the least general type of exception, and in this

case, we actually know the exact type of exception


generated by our code.

{
// Error handling code
}

catch (Exception ex2)


{
// Error handling code
}

finally
{
// Statements to be executed
}

91

Example of try/catch/finally block


class ExceptionHandlingDemo
{
static void Main(string[] args)
{
try
{
int val = 100;
int div = 0;
int resultVal;
resultVal = (val / div);
Console.WriteLine("The result is

: " + resultVal);

}
catch (Exception ex)
{
Console.WriteLine("Exception catch here - details
}
finally
{
Console.WriteLine("Enter finally block ");
}

: " + ex.ToString());

}
}
Output

92

Exception Classes and


User Defined Exceptions

Exception Classes

C# exceptions are represented by classes.

The exception classes in C# are derived from the System. Exception class.

Exception classes derived from System. Exception are


o

System.ApplicationException : Supports exceptions generated by Application programs

System.SystemException : base class for all the predefined system exception like System.IO.IOException,
System.IndexOutOfRangeException, System.DivideByZeroException, System.OutOfMemoryException etc.

The exception object has important properties like Message, StackTree, Targetsite to better understand exception.

94

User-Defined Exceptions
User defined exceptions (also known as Application exception) are explicitly raised by Application on its own condition

User defined exceptions are derived from Exception class.

Exception

User-Defined Exception

New class
Derived from Exception class

95

User-Defined Exceptions - Example


public class TempIsZeroException : Exception
{
public TempIsZeroException(string message) : base(message) { }
}

1. Inherit the new exception class from


Exception class

2. Provide common constructors that


are used by exceptions

class TestTemperature
{
static void PrintTemperature(int iTemperature)
{
if (iTemperature == 0)
throw (new TempIsZeroException("Zero Temperature found"));
else
Console.WriteLine("Temperature: {0}", iTemperature);
}
static void Main(string[] args)
{
try
{
PrintTemperature(0);
}
catch (TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}

3. Throw the exception

Output

96

APIs in C# .net

APIs and examples


There are several in built APIs in C#.
Makes developer job easy.
Reduces the number of lines of code.
Avoids unnecessary implementation and the wastage of memory.
Example of such APIs,
Comparing the strings
Converting a value to ASCII
Converting a string to uppercase
Sorting an collection of items.

98

Vous aimerez peut-être aussi