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

C# Unit-5

The document discusses interfaces, operator overloading, delegates, events, and exception handling in C#: Interfaces define members that classes implement. Operators can be overloaded to define custom behavior. Delegates allow methods to be passed as arguments. Events use delegates to notify subscribers. Exception handling uses try/catch to gracefully handle errors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

C# Unit-5

The document discusses interfaces, operator overloading, delegates, events, and exception handling in C#: Interfaces define members that classes implement. Operators can be overloaded to define custom behavior. Delegates allow methods to be passed as arguments. Events use delegates to notify subscribers. Exception handling uses try/catch to gracefully handle errors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT V

Interfaces

 Interfaces define properties, methods, and


events, which are the members of the interface.
 Interfaces contain only the declaration of the
members.
 It is the responsibility of the deriving class to
define the members.

EXAMPLE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InterfaceApplication
{
publicinterfaceITransaction
{
void showTransaction();
double getAmount();
Transaction(string c, string d, double a);
}
publicclassTransaction : ITransaction
{
privatestring tcode;
privatestring date;
privatedouble amount;
public Transaction(string c, string d, double a)
{
tcode = c;
date = d;
amount = a;
}
publicdouble getAmount()

1
{
return amount;
}
publicvoid showTransaction()
{
Console.WriteLine("Transaction: {0}",tcode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}", getAmount());
}
}
classTester
{
staticvoid Main(string[] args)
{
Transaction t1 =
newTransaction("001","8/2/2019",78900.00);
Transaction t2 = new Transaction ("002", "9/2/2019" ,

451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}
}

Operator Overloading

 Overloaded operators are functions with special


names the keyword operator followed by the symbol
for the operator being defined.
 similar to any other function, an overloaded
operator has a return type and a parameter list.

EXAMPLE

2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace overloading
{
classCalculate
{
publicint n1, n2;
public Calculate(int no1, int no2)
{
n1 = no1;
n2 = no2;
}

publicstaticCalculateoperator + (Calculate c1,Calculate


c2)
{
c1.n1=+c2.n1;
c1.n2=+c2.n2;
return c1;
}
publicvoid print()
{
Console.WriteLine("Number 1: " +n1);
Console.WriteLine("Number 2: " +n2);
Console.ReadKey();
}
}
classover
{
staticvoid Main(string[] args)
{
Calculate c = newCalculate(20,-40);
c.print();
Calculate c3 = newCalculate();
c3 = +c;
c3.print();
Console.ReadKey();

3
}
}
}
OUTPUT

Number 1:20

Number 2: -40

Delegates

 A delegate is a reference type variable that


holds the reference to a method.
 The reference can be changed at runtime.
 All delegates are implicitly derived from
the System.Delegate class

Declaring Delegates

 Delegate declaration determines the methods that


can be referenced by the delegate

Syntax for delegate declaration is:

delegate<return type><delegate-name><parameter
list>

public delegate intMyDelegate (string s);

Instantiating Delegates

 Once a delegate type is declared, a delegate


object must be created with thenew keyword and be
associated with a particular method.

4
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
 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
 delegate intNumberChanger(int n);

EXAMPLE

namespaceDelegateAppl
{
classTestDelegate
{
staticintnum = 10;
public static intAddNum(int p)
{
num += p;
returnnum;

5
}
public static intMultNum(int q)
{
num *= q;
returnnum;
}
public static intgetNum()
{
returnnum;
}
static void Main(string[] args)
{
//create delegate instances
NumberChangernc;
NumberChanger nc1 = newNumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
nc += nc2;
//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
Result

Value of Num: 75
6
Using Delegates

 The delegateprintString can be used to reference


method that takes a string as input and returns
nothing.

Events

• Events are user actions such as key press, clicks,


mouse movements, etc.

• Applications need to respond to events when they


occur

Using Delegates with Events

• A publisher is an object that contains the


definition of the event and the delegate

• A subscriber is an object that accepts the event


and provides an event handler

Declaring Events

• To declare an event inside a class, first a


delegate type for the event must be declared

syntax

– public delegate string MyDel(string str);

– event MyDelMyEvent;

7
public delegate string MyDel(string str);

EXAMPLE
classEventProgram
{
eventMyDelMyEvent;
publicEventProgram()
{
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username)
{
return "Welcome " + username;
}
static void Main(string[] args)
{
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("Tutorials Point");
Console.WriteLine(result);
} }}
Output

Welcome Tutorials Point

Exception Handling

8
• 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

try
{
// statements causing exception
}
catch(ExceptionName e1 )
{
// error handling code

9
}
catch(ExceptionName e2 )
{
// error handling code
}
catch(ExceptionNameeN )
{
// error handling code
}
Finally
{
// statements to be executed
}
Nested try
try
{
//do something
Try
{
//do something
if exception is thrown, don't go to parent catch
}
catch(Exception ex) {...} }
catch(Exception ex) { .... }
Exception Classes in C#

10
• The System.ApplicationException class supports
exceptions generated by application programs

• The System.SystemException class is the base class


for all predefined system exception

Exception Class Description

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 deferencing a null
object.

System.DivideByZeroException Handles errors generated


from dividing a dividend
with zero.

System.InvalidCastException Handles errors generated


during typecasting.

11
System.OutOfMemoryException Handles errors generated
from insufficient free
memory.

System.StackOverflowException Handles errors generated


from stack overflow.

Handling Exceptions

• These error handling blocks are implemented using


the try, catch, and finallykeywords

classDivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)

12
{
Console.WriteLine("Exception caught: {0}", e);
}
Finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
Throwing Objects

• You can throw an object if it is either directly or


indirectly derived from theSystem.Exception class.

• Catch(Exception e) { ... Throw e }

Classification of Errors

13
Logic Errors

• Your code may compile and run without any Syntax


Errors or Run-time Errors, but the output of an
operation may produce unwanted or unexpected
results in response to user actions.

• These types of errors are called Logic Errors. That


means, Logic errors are those that appear once the
application is in use.

• These are generally the hardest type to fix, since


it is not always clear where they originate.

• Also the development environment does not see


anything wrong in the document and therefore cannot
point out a problem

Run-time Errors

• Run-time errors are those that appear only after


you compile and run your code. It will occur when
your program attempts an operation that is

14
impossible to carry out. You can fix most run-time
errors by rewriting the faulty code, and then
recompiling and running it.

• Ex: A program error may result from an attempt to


divide by zero

• int a = 5; int b = 0; int c = a /b;

• When you compile this program, compiler won't show


any Syntax Error. But when you run this code, the
compiler show "Attempted to divide by zero".

Syntax Errors

• Syntax Errors, also known as Compilation errors are


the most common type of errors. Most Syntax errors
are caused by mistakes that you make when writing
code. If you are using the coding environment like
Visual Studio, it is able to detect them as soon as
you write them, also you can fix them easily as
soon as they occur. When you compile your
application in the development environment, the
compiler would point out where the problem is so
you can fix it instantly.

• Ex: When you forgot to type a semicolon (;) after


the statement, the compiler shows the syntax error
and it would point out where the problem occurred.

15
Checked and Unchecked Operator

Checked Operator:

• When due to a limitation of a datatype, like an


int, we lose the data or get the unpredictable
value, for skipping this garbage value and generate
the "Stackoverflow exception" , use a checked
operator.

Unchecked Operator:

• it is the reverse of a checked operator where you


get the garbage value in the actual scenario. It is
used by default in C#.

EXAMPLE

try
{
int a = 200000;
int b = 300000;
int c = checked(a * b);
Console.WriteLine(c.ToString());
}
catch(Exception ex)
{
Console.WriteLine("Your multiplication cross the limit"
);
}

16
Console.ReadKey();
try
{
int a = 2000000;
int b = 3000000;
int c =unchecked(a * b);
Console.WriteLine(c.ToString());
}
catch(Exception ex)
{
Console.WriteLine("Your multiplication cross the limit"
);
}
Console.ReadKey();
}

17

You might also like