Events in C#
What is Event?
How to Declare an Event.
Example
What is Event?
Events are user actions such as Keypress,button click etc. or some
occurrences such as system generated notifications.
Applications need to respond to events when they occur.
For example. If you have subscribed to any Youtube Chanel and if
any new videos is uploaded you will receive notifications.
The event is encapsulated delegate.
When the state of the application changes, events and
delegates give the notification to the client application.
Declaring and using 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.
Events use the publisher-subscriber model.
Publisher class-The class containing the event which is
used to publish the event.
Subscriber Class: The class that accepts the event.
The publishers determines when an event is raised and
subscriber determines what action is taken in response
An Event can have so many subscribers.
Events are basically used for the single user action like
button click.
Declaring and using 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.
Example
namespace EventDemo
{
public delegate string demoDelegete(string str);
class MyEvents
{
event demoDelegete myEvent;
public MyEvents()
{
[Link]+=new demoDelegete([Link]);
}
public string Display(string name)
{
return name;
}
static void Main(string[] args)
{
MyEvents e = new MyEvents();
string res = [Link]("jack");
[Link]("Welcome:" + res);
[Link]();
}
}
}
Operator Overloading
What is Operator Overloading
Syntax for C# operator Overloading
Example: Addition of complex numbers.
Operator Overloading
Operator overloading is the ability to make an
operator perform different operations on operands
of different data types.
In C#, it is possible to make operators work with
user-defined data types like classes. That means
C# has the ability to provide the operators with a
special meaning for a data type, this ability is
known as operator overloading.
For example, we can overload the + operator in a
class like String so that we can concatenate two
strings by just using +.
Syntax for C# operator
Overloading
To overload an operator in C#, we use a special operator function. We define
the function inside the class or structure whose objects/variables we want the
overloaded operator to work with.
The Syntax for Operator Overloading in C# is shown below.
Here,
1. The return type is the return type of the function.
2. the operator is a keyword.
3. Op is the symbol of the operator that we want to overload. Like: +, <, -, ++,
etc.
4. The type must be a class or struct. It can also have more parameters.
5. It should be a static function.
Which all Operator We can
Overload
We can overload all the binary operators i.e +,
-, *, /, %, &, |, <<, >>.
We can overload all the unary operators i.e. +
+, –, true, false, + , -, ~.
Some operators like &&, ||,[] ,() cannot be
overloaded.
We can overload relational operators in pairs.
These are ==, =, <, >, <= , >= etc.
Overriding ToString() method
We know that all objects created in .NET inherit
from the “[Link]” class.
Let us say when we create a class and if we see
the object of the class there are four methods
present in each object. These are are GetType(),
ToString(), GethashCode(), Equals().
When we call ToString() on any object, it returns
to us the Namespace and type name of the class.
This is the default implementation of ToString()
provided [Link] class gives us complete
type name of the class.
using System;
using System;
namespace OverrideTostring
namespace OverrideTostring
{
{
class Program class Program
{ {
static void Main(string[] args) static void Main(string[] args)
{ {
Employee emp = new Employee() { Employee emp = new Employee() { EmpId=
EmpId=100, EmpName="Pradeep", Dept 100, EmpName="Pradeep", DeptName="Comp
Name="Computer Science"}; uter Science"};
[Link]([Link]());
[Link]([Link]()); [Link]();
[Link](); }
}
public class Employee
}
{
} public int EmpId { get; set; }
public string EmpName { get; set; }
public class Employee public string DeptName { get; set; }
{ public override string ToString()
public int EmpId { get; set; } {
public string EmpName { get; set; } return [Link] + " " + [Link] + "
public string DeptName { get; set; } " +[Link];
}
}
}
}
Output
}
Operator Overloading Example
Adding two complex numbers using
Operator overloading
Complex no having Two parts i.e real and
imaginary
using System;
public class Complex
{
public int real; public static void Main()
public int imaginary; {
public Complex(int real, int imag) Complex cnum1 = new Complex(4, 5);
{ Complex cnum2 = new Complex(5, 6);
[Link] = real;
// Add two Complex objects (num1 and num2)
[Link] = imag; through the
}
Complex addition = cnum1 + cnum2;
// Syntax of Operator Overloading
public static Complex operator +(Complex n1, // Print the numbers
Complex n2) [Link]("First complex number: {0}",
{ cnum1);
return new Complex([Link] + [Link], [Link] + [Link]("Second complex number:
[Link]); {0}", cnum2);
} [Link](“The sum of the two numbers:
// Override the ToString method to display an complex {0}", addition);
number in the suitable format: // Hault the output screen
public override string ToString() [Link]();
{
}
return ([Link]("{0} + {1}i", real, imag));
} }
}
UNIT 4
Exception Handling:
Handling Exceptions using try and catch
Raising Exceptions using throw
Pre- defined Exception classes
Custom Exception classes,
What Does Exception
Handling Mean?
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.
What Does Exception
Handling Mean?
KEYWORD DEFINIATON
Try
Used to define a try block. This block holds the code that
may throw an exception.
Catch
Used to define a catch block. This block catches the
exception thrown by the try block
Finally
Used to define the finally block. This block holds the
default code.
throw
Used to throw an exception manually.
SYNTAX
try/catch looks like the following −
try
{
// statements causing exception
}
catch( Exception Class e1 )
{
// error handling code
}
catch( ExceptionClass e2 )
{
// error handling code
}
catch( ExceptionClass eN )
{
// error handling code
}
finally
{
// default code
}
namespace SysExc
{
class Program
{
static void Main(string[] args)
{
int number1, number2, Result;
try
{
[Link]("Enter the first Number");
number1 = [Link]([Link]());
[Link]("Enter the second Number");
number2 = [Link]([Link]());
Result = number1 / number2;
[Link]("result:" + Result);
}
catch (DivideByZeroException)
{
[Link]("Second Number should not be zero");
}
catch (FormatException fe)
{
[Link]("enter only integer numbers");
}
catch (Exception)
{
[Link]("Generic catch block....“)
}
[Link]();
}
}
Pre-defined Exception Classes
Exception Class Description
ArgumentException Raised when a non-null argument that
is passed to a method is invalid.
ArgumentNullException Raised when null argument is passed
to a method.
ArgumentOutOfRangeException Raised when the value of an argument
is outside the range of valid values.
DivideByZeroException Raised when an integer value is divide
by zero.
FileNotFoundException Raised when a physical file does not
exist at the specified location.
FormatException Raised when a value is not in an
appropriate format to be converted from
a string by a conversion method such
as Parse.
IndexOutOfRangeException Raised when an array index is outside
the lower or upper bounds of an array
or collection.
InvalidOperationException Raised when a method call is invalid in
an object's current state.
OutOfMemoryException Raised when a program does not get
enough memory to execute the code.
StackOverflowException Raised when a stack in memory
overflows.
TimeoutException The time interval allotted to an
operation has expired.
Raising Exceptions using
throw
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.
C# throw Keyword Syntax
Following is the syntax of raising an exception using
throw keyword in c#.
throw e;
Here, e is an exception that is derived from the
Exception class and throw keyword to throw an
exception.
Assemblies
The Role of .NET Assemblies,
Understanding the format of .NET
Assemblies,
single file assembly, multifile assembly
, Private and Shared Assemblies.