0% found this document useful (0 votes)
11 views45 pages

unit 3

This document outlines the syllabus for a .NET course, covering key topics such as data types, operators, garbage collection, indexers, delegates, events, exception handling, and decision-making structures in C#. It details the functionality and syntax of various programming constructs in C#, including operators, loops, arrays, and exception handling mechanisms. Additionally, it explains the concepts of garbage collection and event handling in the context of C# programming.

Uploaded by

Tech Coder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views45 pages

unit 3

This document outlines the syllabus for a .NET course, covering key topics such as data types, operators, garbage collection, indexers, delegates, events, exception handling, and decision-making structures in C#. It details the functionality and syntax of various programming constructs in C#, including operators, loops, arrays, and exception handling mechanisms. Additionally, it explains the concepts of garbage collection and event handling in the context of C# programming.

Uploaded by

Tech Coder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

.

NET

Prepared by:
Sumit Chhillar
(Assistant Professor)
SYLLABUS
UNIT III

Data Types; Operators; Garbage Collection; Indexer(One


Dimension) and property; Delegates and events (Multicasting;
Multicasting Event); Exception Handling, Conditional
Statements- If- Then, If-Then-Else, Nested If, Select Case,
Looping Statement- Do loop, For Loop, For Each-Next Loop,
While Loop, Arrays- Static and Dynamic.
Operators
• An operator is a symbol that tells the compiler to perform
specific mathematical or logical manipulations. C# has rich set
of built-in operators and provides the following type of
operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
Arithmetic Operators

• Assume variable A holds 10 and


variable B holds 20 then −
Relational Operators

• Assume variable A holds 10 and


variable B holds 20, then −
Logical Operators

• Assume variable A holds Boolean value true


and variable B holds Boolean value false, then

Bitwise Operators

• Bitwise operator works on bits and perform bit


by bit operation.
Assignment Operators
Miscellaneous Operators

• There are few other important operators including sizeof, typeof and ? : supported
by C#.
Garbage Collection in C#
| .NET Framework
• Automatic memory management is made possible
by Garbage Collection in .NET Framework. When a class
object is created at runtime, certain memory space is allocated
to it in the heap memory. However, after all the actions related
to the object are completed in the program, the memory space
allocated to it is a waste as it cannot be used. In this case,
garbage collection is very useful as it automatically releases
the memory space after it is no longer required.
• Garbage collection will always work on Managed Heap and
internally it has an Engine which is known as
the Optimization Engine.
• Garbage Collection occurs if at least one of multiple
conditions is satisfied. These conditions are given as follows:
• If the system has low physical memory, then garbage
collection is necessary.
• If the memory allocated to various objects in the heap memory
exceeds a pre-set threshold, then garbage collection occurs.
• If the GC.Collect method is called, then garbage collection
occurs. However, this method is only called under unusual
situations as normally garbage collector runs automatically.
• Marking Phase: A list of all the live objects is created during the marking
phase. This is done by following the references from all the root objects.
All of the objects that are not on the list of live objects are potentially
deleted from the heap memory.
• Relocating Phase: The references of all the objects that were on the list of
all the live objects are updated in the relocating phase so that they point to
the new location where the objects will be relocated to in the compacting
phase.
• Compacting Phase: The heap gets compacted in the compacting phase as
the space occupied by the dead objects is released and the live objects
remaining are moved. All the live objects that remain after the garbage
collection are moved towards the older end of the heap memory in their
original order.
• Generation 0 : All the short-lived objects such as temporary variables are
contained in the generation 0 of the heap memory. All the newly allocated
objects are also generation 0 objects implicitly unless they are large
objects. In general, the frequency of garbage collection is the highest in
generation 0.
• Generation 1 : If space occupied by some generation 0 objects that are not
released in a garbage collection run, then these objects get moved to
generation 1. The objects in this generation are a sort of buffer between the
short-lived objects in generation 0 and the long-lived objects in generation
2.
• Generation 2 : If space occupied by some generation 1 objects that are not
released in the next garbage collection run, then these objects get moved to
generation 2. The objects in generation 2 are long lived such as static
objects as they remain in the heap memory for the whole process duration.
C# - Indexers

• An indexer allows an object to be indexed such as an array.


When you define an indexer for a class, this class behaves
similar to a virtual array. You can then access the instance of
this class using the array access operator ([ ]).
• Syntax
• A one dimensional indexer has the following syntax −
• element-type this[int index]
• { // The get accessor. Get
• { // return the value specified by index }
• // The set accessor. set
• { // set the value specified by index } }
Use of Indexers

• Declaration of behavior of an indexer is to some extent similar


to a property. similar to the properties, you
use get and set accessors for defining an indexer. However,
properties return or set a specific data member, whereas
indexers returns or sets a particular value from the object
instance. In other words, it breaks the instance data into
smaller parts and indexes each part, gets or sets each part.
• Defining a property involves providing a property name.
Indexers are not defined with names, but with
the this keyword, which refers to the object instance.
Overloaded Indexers

• Indexers can be overloaded. Indexers can also


be declared with multiple parameters and each
parameter may be a different type. It is not
necessary that the indexes have to be integers.
C# allows indexes to be of other types, for
example, a string.
C# - Delegates

• C# delegates are similar to pointers to


functions, in C or C++. A delegate is a
reference type variable that holds the reference
to a method. The reference can be changed at
runtime.
• Delegates are especially used for
implementing events and the call-back
methods. All delegates are implicitly derived
from the System.Delegate class.
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 −
• 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);
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.
• 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.
C# - Events

• Events are user actions such as key press,


clicks, mouse movements, etc., or some
occurrence such as system generated
notifications. Applications need to respond to
events when they occur. For example,
interrupts. Events are used for inter-process
communication.
Using Delegates with
Events
• The events are declared and raised in a class and associated with the
event handlers using delegates within the same class or some other
class. The class containing the event is used to publish the event.
This is called the publisher class. Some other class that accepts this
event is called the subscriber class. Events use the publisher-
subscriber model.
• A publisher is an object that contains the definition of the event and
the delegate. The event-delegate association is also defined in this
object. A publisher class object invokes the event and it is notified to
other objects.
• A subscriber is an object that accepts the event and provides an
event handler. The delegate in the publisher class invokes the
method (event handler) of the subscriber class.
C# - Exception Handling

• An exception is a problem that arises during the execution of a program. A C#


exception is a response to an exceptional circumstance that arises while a program
is running, such as an attempt to divide by zero.
• Exceptions provide a way to transfer control from one part of a program to another.
C# exception handling is built upon four keywords: try, catch, finally, and throw.
• try − A try block identifies a block of code for which particular exceptions is
activated. It is followed by one or more catch blocks.
• catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
• finally − The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be
closed whether an exception is raised or not.
• throw − A program throws an exception when a problem shows up. This is done
using a throw keyword.
Syntax

• Assuming a block raises an exception, a method catches an exception


using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following −
• try { // statements causing exception }
• catch( ExceptionName e1 ) { // error handling code }
• catch( ExceptionName e2 ) { // error handling code }
• catch( ExceptionName eN ) { // error handling code }
• finally { // statements to be executed }
• 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.
Exception Classes in C#

• System.IO.IOException
Handles I/O errors.
• System.IndexOutOfRangeException
Handles errors generated when a method refers to an array index out of
range.
• System.ArrayTypeMismatchException
Handles errors generated when type is mismatched with the array type.
• System.NullReferenceException
Handles errors generated from referencing a null object.
• System.DivideByZeroException
Handles errors generated from dividing a dividend with zero.
• System.InvalidCastException
Handles errors generated during typecasting.
• System.OutOfMemoryException
Handles errors generated from insufficient
free memory.
• System.StackOverflowException
Handles errors generated from stack overflow.
Handling Exceptions
C# - Decision Making

• Decision making structures requires the


programmer to specify one or more conditions
to be evaluated or tested by the program, along
with a statement or statements to be executed
if the condition is determined to be true, and
optionally, other statements to be executed if
the condition is determined to be false.
C# - if Statement

• An if statement consists of a boolean expression followed by


one or more statements.
• Syntax
• The syntax of an if statement in C# is −
• if(boolean_expression)
• { /* statement(s) will execute if the boolean expression is true
*/ }
• If the boolean expression evaluates to true, then the block of
code inside the if statement is executed. If boolean expression
evaluates to false, then the first set of code after the end of the
if statement(after the closing curly brace) is executed.
C# - if...else Statement

• An if statement can be followed by an optional else statement,


which executes when the boolean expression is false.
• Syntax
• The syntax of an if...else statement in C# is −
• if(boolean_expression)
• { /* statement(s) will execute if the boolean expression is true
*/ } else { /* statement(s) will execute if the boolean
expression is false */ }
• If the boolean expression evaluates to true, then the if
block of code is executed, otherwise else block of code is
executed.
C# - Nested if
Statements
• It is always legal in C# to nest if-else statements, which
means you can use one if or else if statement inside
another if or else if statement(s).
• Syntax
• The syntax for a nested if statement is as follows −
• if( boolean_expression 1) { /* Executes when the boolean
expression 1 is true */ if(boolean_expression 2) { /*
Executes when the boolean expression 2 is true */ } }
• You can nest else if...else in the similar way as you have
nested if statement.
C# - Loops

• There may be a situation, when you need to


execute a block of code several number of
times. In general, the statements are executed
sequentially: The first statement in a function
is executed first, followed by the second, and
so on.
• Programming languages provide various
control structures that allow for more
complicated execution paths.
C# - While Loop

• A while loop statement in C# repeatedly executes a target statement


as long as a given condition is true.
• Syntax
• The syntax of a while loop in C# is −
• while(condition)
• { statement(s); }
• Here, statement(s) may be a single statement or a block of
statements. The condition may be any expression, and true is any
non-zero value. The loop iterates while the condition is true.
• When the condition becomes false, program control passes to the
line immediately following the loop.
C# - For Loop

• A for loop is a repetition control structure that allows


you to efficiently write a loop that needs to execute a
specific number of times.
• Syntax
• The syntax of a for loop in C# is −
• for ( init; condition; increment )
• { statement(s); }
• for (int a = 10; a < 20; a = a + 1)
{ Console.WriteLine("value of a: {0}", a); }
C# - Do...While Loop

• Unlike for and while loops, which test the loop condition at the start of the
loop, the do...while loop checks its condition at the end of the loop.
• A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
• Syntax
• The syntax of a do...while loop in C# is −
• do { statement(s); } while( condition );
• Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop execute once before the condition is tested.
• If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop execute again. This process repeats until the given
condition becomes false
C# - Arrays

• An array stores a fixed-size sequential collection of elements of the


same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of
the same type stored at contiguous memory locations.
• Instead of declaring individual variables, such as number0,
number1, ..., and number99, you declare one array variable such as
numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables. A specific element in an array is
accessed by an index.
• All arrays consist of contiguous memory locations. The lowest
address corresponds to the first element and the highest address to
the last element.
Declaring Arrays

• To declare an array in C#, you can use the following syntax −


• datatype[] arrayName; where,
• datatype is used to specify the type of elements in the array.
• [ ] specifies the rank of the array. The rank specifies the size
of the array.
• arrayName specifies the name of the array.
• For example,
• double[] balance;
Initializing an Array

• Declaring an array does not initialize the array


in the memory. When the array variable is
initialized, you can assign values to the array.
• Array is a reference type, so you need to use
the new keyword to create an instance of the
array. For example,
• double[] balance = new double[10];
Assigning Values to an
Array
• You can assign values to individual array elements, by using the index
number, like −
• double[] balance = new double[10]; balance[0] = 4500.0; You can assign
values to the array at the time of declaration, as shown −
• double[] balance = { 2340.0, 4523.69, 3421.0};
• You may also omit the size of the array, as shown −
• int [] marks = new int[] { 99, 98, 92, 97, 95}; You can copy an array
variable into another target array variable. In such case, both the target and
source point to the same memory location −
• int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks;
• When you create an array, C# compiler implicitly initializes each array
element to a default value depending on the array type. For example, for an
int array all elements are initialized to 0.
Accessing Array
Elements
• An element is accessed by indexing the array
name. This is done by placing the index of the
element within square brackets after the name
of the array. For example,
• double salary = balance[9];
C# - Multidimensional
Arrays
• C# allows multidimensional arrays. Multi-
dimensional arrays are also called rectangular
array. You can declare a 2-dimensional array
of strings as −
• string [,] names;
Two-Dimensional Arrays

• The simplest form of the multidimensional array is the 2-


dimensional array. A 2-dimensional array is a list of one-
dimensional arrays.
• Initializing Two-Dimensional Arrays
• Multidimensional arrays may be initialized by specifying
bracketed values for each row. The Following array is with 3
rows and each row has 4 columns.
• int [,] a = new int [3,4]
• { {0, 1, 2, 3} , /* initializers for row indexed by 0 */
• {4, 5, 6, 7} , /* initializers for row indexed by 1 */
• {8, 9, 10, 11} /* initializers for row indexed by 2 */ };

You might also like