0% found this document useful (0 votes)
52 views

.NET Programming - Unit 3

This document discusses delegates and events in C# and managing console I/O operations. It defines delegates as objects that encapsulate methods, and events as delegate types that allow classes to notify other objects of events. It describes the four steps to using delegates: declaration, defining methods, instantiation, and invocation. It also covers console input/output streams, formatting output using placeholders, and numeric formatting options like currency, integer, exponential, fixed point, and custom formats.

Uploaded by

PALLAVI Y
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

.NET Programming - Unit 3

This document discusses delegates and events in C# and managing console I/O operations. It defines delegates as objects that encapsulate methods, and events as delegate types that allow classes to notify other objects of events. It describes the four steps to using delegates: declaration, defining methods, instantiation, and invocation. It also covers console input/output streams, formatting output using placeholders, and numeric formatting options like currency, integer, exponential, fixed point, and custom formats.

Uploaded by

PALLAVI Y
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Delegates and Events

Delegate:
● Delegate means a method acting for another method.
● A delegate in C# is a class type object and is used to invoke a method that has been
encapsulated into it at the time of its creation.
● A delegate object is a special type of object that contains the details of a method rather
than data.
● Delegates are used for two purposes: Callback and Event handling.
● Creating and using delegates involve four steps:
1. Delegate declaration.
2. Delegate methods definition.
3. Delegate instantiation.
4. Delegate invocation.
● System.Delegate class is used for delegate declaration.
● Delegate methods are functions whose signature matches the delegate signature exactly.
● The delegate instance holds the reference to delegate methods. The instance is used to
invoke the methods indirectly.
Delegate Declaration
modifier delegate return-type delegate-name (parameters);
● This represents a class type derived from System.Delegate.
● The delegate is the keyword to be used.
● The return-type represents the return type of the delegate.
● Parameters identify the signature of the delegate.
● The modifier controls the accessibility of the delegate and it is optional.
● The delegate may be defined inside a class, outside all classes, or as the top level object
in a namespace.
● Delegate types are implicitly sealed and therefore it is not possible to derive any type
from a delegate type.
Delegate methods
The methods whose references are encapsulated into a delegate instance are known as delegate
methods or callable entities. The signature and return type of delegate methods must exactly
match the signature and return type of the delegate. Ex:
The delegate
delegate void result(int a);
can refer or encapsulate references to the following methods,
public void f1(int x) {
return x*x;
}
public void f2(int y) {
return y+y;
}
In the above case, the signature and return type of methods match the signature and type of the
delegate.
Delegate Instantiation
C# provides a special syntax for instantiating their instances.
new delegate-name (expression);
● Here the delegate-name is the name of the delegate declared earlier whose object is to be
created. The expression must be a method name or a value of a delegate-name.
● If it is a method name it's signature and return type must be the same as those of the
delegate. If no matching method exists or more than one matching method exists, then an
error occurs.
Ex:
delegate void result(int a); //delegate declaration
class delegatetest {
public void fun(int x, int y) { //signature not match
return x*x;
}
public void fun(int y) { //signature matches
return y+y;
}
result r = new result(fun); //delegate instantiation
}
Here, we have two methods with the same name but with different signatures. The delegate r is
initialized with the reference to the second fun method because that method exactly matches the
signature and return type of result.
Delegate Invocation
C# uses a special syntax for invoking a delegate. When a delegate is invoked, it in turn invokes
the method whose reference has been encapsulated into the delegate.
delegate-object(parameters);
Ex:
r(10);
Example 1:
Example 2:

Multicast Delegates
It is possible for certain delegates to hold and invoke multiple methods. Such delegates are called
Multicast delegates. Also known as combinable delegates, must satisfy the following conditions:
● The return type of the delegate must be void.
● None of the parameters of the delegate type can be declared output parameters.
Example 3:

Events:
● An event is a delegate type class member that is used by the object or class to provide a
notification to other objects that an event has occurred.
● The client object can act on an event by adding an event handler to the event.
● The syntax
modifier event type event-name;
● The keyword event is used.
● The type of an event declaration must be a delegate type and the delegate must be as
accessible as the event itself.
Ex: public event Eventhandler click;
Here Eventhandler is a delegate and click is a event.
Example 4:
Managing Console I/O Operations

Console Class: The methods for reading from and writing to the console are provided by the
System.Console class. This class gives us access to the standard input, standard output and
standard error streams.
Stream Object Represents

Console.In Standard Input

Console.Out Standard Output

Console.Error Standard Error

● Console.In gets input by default from the keyboard. We can also redirect it to receive
input from a file.
● Console.Out sends output to the screen by default. We can also redirect the output to a
file.
● Console.Error sends error messages to the screen.

Console Input: This stream object supports two methods for obtaining input from the keyboard.
● Read() returns a single character as int. Returns -1 if no more characters are available.
● ReadLine() returns a string containing a line of text. Returns null if no more lines are
available.

Console Output: This stream object supports two methods for writing to the console.
● Write() displays one or more values to the screen without a newline character.
● WriteLine() displays one or more values to the screen but adds a newline character at the
end of the output.

Formatted Output: We can produce formatted output using the overloaded WriteLine() method.
This method takes a string containing a format and a list of variables whose values have to be
printed out. The general form is
Console.WriteLine(format-string, v1, v2,....);
The format string contains both static text and markers which indicate:
● where the values are to be printed.
● How the values are to be formatted.
● A marker is an index number in curly brackets, that indicates which variable of the
argument list is to be substituted.
Ex: Console.WriteLine("The values are {0} and {1}", a, b);

Console.WriteLine("The values are"+ a);


Console.WriteLine(" and "+ b);

Console.WriteLine("The values are"+ a +"and" +b);


The values are 25 and 36

Example:
using System;
class num {
public static void Main() {
int a=2, b=5;
Console.WriteLine("The values are {0} and {1}", a, b);
}
}
Output: The values are 2 and 5

Numeric Formatting: The marker {} also called as placeholder can optionally contain various
format characters to specify the nature of numeric format. C# supports two methods of numeric
format:
1. Standard format
2. Custom format

Standard Numeric Format: It consists of a numeric format character and optionally a precision
specifier. The general format is
{n:fc [p]} or {n:fcp}
Here n is the index number of the argument to be substituted, fc is the format character and p is
the precision specifier.
The list of format characters that can be used for formatting the output of numbers.
● Currency format converts the numerical value to a string containing a locale-specific
currency symbol. By default the dollar symbol is added. It can be changed using a
NumberFormatInfo object.
Ex: (" {0:C}", 5000.1589) Results $5000.20

● Integer format converts a given numerical value to an integer of base 10. The minimum
number of digits is determined by the precision specifier.
Ex: (" {0:D6}", 5589) Results 005589
(" {0:D2}", 5589) Results 5589 (Ignores the precision specifier)

● Exponential formatting character E or e converts a given value to a string in the form of


mantissa and exponents.
Ex: (" {0:E}", 5589.1236) Results 5.58912E+003
(" {0:E3}", 5589.1236) Results 5.589E+003

● Fixed point format: This converts the given value to a string containing decimal places as
decided by the precision specifier. By default two decimal places are assumed.
Ex: (" {0:F}", 5589.1233) Results 5589.12
(" {0:F4}", 5589.126689) Results 5589.1267

● Number format: This format produces the output with the embedded commas. By default
two decimal places are assumed.
Ex: (" {0:N}", 5589.1233) Results 5,589.12
(" {0:N4}", 12589.5) Results 12,589.5000

Custom Numeric Format: C# supports some special characters that are used to form a template
for nature of output.
● Zero Placeholder (0): This is used to format integer output. If the number has a digit in
the position at which the zero appears in the format string, the digit will appear in the
output; otherwise zero will appear. If the number of zeros is less than the number of digits
then all the digits will appear.
Ex: (" {0 :00000}", 5589) Results 05589
(" {0 : 00}", 2589) Results 2589

● Space Placeholder (#): We can also use pound character to format integer output. It works
same as zero placeholder. But instead of zero, blank appears if there is no digit in that
position.
Ex: (" {0 :#####}", 5589) Results 5589
(" {0 : ##}", 2589) Results 2589

● Decimal Separator (.): The position of the decimal point in the output may be decided by
placing a period character in the format string.
Ex: (" {0 :##.00}", 24.56823) Results 24.57
(" {0 : ##.0000}", 24.56) Results 24.5600

● Comma Separator (,): The character comma can be used along with the placeholder zero
and pound characters to separate group of digits in the integer part of the output.
Ex: (" {0 :#,#}", 24561) Results 24,561
(" {0 :#,#.00}", 24561.56823) Results 24,561.57
(" {0 : #, #.0000}",12546380.562341) Results 12,546,380.5623

● Percent Notation (%): The character percent (%) is used to display a number in
percentage.
Ex: (" {0 :##.00%}", 0.235) Results 23.50%
(" {0 :##.0%}", 0.568) Results 56.8%
(" {0 : 00%}",0.1254) Results 12%

Managing Errors and Exceptions

Debugging is a process of identifying and fixing errors in a software program so as to ensure


that it behaves in the intended manner.
Visual Studio has an inbuilt debugger that helps programmers to locate and fix errors at
runtime. The .NET Framework also provides a command line debugging tool called cordbg.

There are two types of errors: Compile time errors and Runtime errors.

Compile time errors: All syntax errors will be detected and displayed by the C# compiler and
they are called Compile time errors. The common errors are:
● Missing semicolon.
● Missing brackets.
● Misspelling of identifiers and keywords.
● Missing double quotes.
● Use of undeclared variables.
● Bad references to objects.
● Incompatible types in assignments.

Runtime errors: A program may compile successfully but may not run properly. This is due to
wrong logic and they are called Compile time errors. The common errors are:
● Dividing an integer by zero.
● Accessing an element that is out of the bounds of an array.
● Trying to store a value into an array of an incompatible class or type.
● Attempting to use negative size of an array.
● Passing parameter that is not a valid.

Exceptions: An exception is a condition that is caused by a run time errors in the program.
When the C# compiler encounters an error, it creates an exception object and throws it. If the
exception is not caught and handled properly the compiler will display an error message and will
terminate the program. If we want the program to continue with the execution of the remaining
code, then we should try to catch the exception object thrown by the error condition and then
display an appropriate message for taking corrective actions. This task is known as exception
handling.
The mechanism has following tasks:
1. Find the problem.
2. Inform that an error has occurred.
3. Receive the error information.
4. Take corrective actions.

Common C# Exceptions
Syntax of Exception Handling

…….
try {
Statements
}
catch(Exception e) {
Statements
}

Multiple catch statements

…….
try {
Statements
}
catch(Exception1 e) {
Statements
}
catch(Exception2 e) {
Statements
}
catch(Exception3 e) {
Statements
}
catch(Exception4 e) {
Statements
}
.
.
catch(Exceptionn e) {
Statements
}

General catch handler

…….
try {
Statements
}
catch {
Statements
}

Using finally statement

…….
try {
Statements
}
finally {
Statements
}

OR

…….
try {
Statements
}
catch(Exception1 e) {
Statements
}
catch(Exception2 e) {
Statements
}
..
..
finally {
Statements
}

Nested try blocks

…….
try {
…….
……..
try {
…….
……..
}
catch(Exception1 e) {
Statements
}
catch(Exception2 e) {
Statements
}
..
..

finally {
Statements
}
}
catch(Exception1 e) {
Statements
}
catch(Exception2 e) {
Statements
}
..
..

finally {
Statements
}

Throwing our own exceptions


● In C# we can throw our own exceptions.
● The keyword throw is used. The syntax is
throw new throwableclass();
Ex: throw new MyException();

Example
using System;
class MyException:Exception {
public MyException(string Message ) : base(Message) {
}
public MyException() {
}
public MyException(string Message, Exception inner) : base(Message, inner) {
}
}
class MyExceptionTest {
public static void Main() {
int x=3, y=10000;
float z;
try {
z=(float) x/(float)y;
if(z<0.1)
throw new MyException("Small Number");
}
catch(MyException e) {
Console.WriteLine("Exception is caught");
Console.WriteLine(e.Message);
}
finally {
Console.WriteLine("Exception!!");
}
}
}

Exception is caught
Small Number
Exception!!

Checked and Unchecked Operations


● In arithmetic operations and conversion of integer types, the stack overflow is the
problem.
● C# supports two operators, checked and unchecked which are used for checking or
unchecking stack overflows during program execution.
● If an operation is checked then an exception will be thrown if overflow occurs.
● If an operation is not checked then no exception will be raised if overflow occurs but we
will lose data.
Example
int n=100000, m=500000;
try {
int p=unchecked(n*m);
}
catch(OverflowException e) {
Console.WriteLine(e);
}

Using Exceptions for debugging

You might also like