c#
c#
C# try/catch
Example:
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e)
{
Console.WriteLine(e);
}
Output:
System.DivideByZeroException: Attempted to divide by zero.
Rest of the code
C# finally
C# finally block is used to execute important code which is to be executed whether exception is
handled or not. It must be preceded by catch or try block.
Example:
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
}
finally
{
Console.WriteLine("The 'try catch' is finished.");
}
Rest of the code
Example:
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else
{
Console.WriteLine("Access granted - You are old enough!");
}
}
In C#, You can use more than one catch block with the try block. Generally, multiple catch
block is used to handle different types of exceptions means each catch block is used to
handle different type of exception.
It is possible to catch multiple (different) exceptions that may be thrown in a try block using
multiple (or a series of) catch blocks.
C# does not allow you to use multiple catch block for the same type of exception
In general, the catch block is checked within the order in which they have occurred in the
program. If the given type of exception is matched with the first catch block, then first catch
block executes and the remaining of the catch blocks are ignored. And if the starting catch
block is not suitable for the exception type, then compiler search for the next catch block.
Syntax:
try {
// Your code
// Code
// Code
.
.
.
.
Example:
// C# program to illustrate the
// use of multiple catch block
using System;
class GFG {
// Main Method
static void Main()
{
// Catch block 1
// Catch block 2
Output:
Number: 8
Divisor: 2
Quotient: 4
Number: 17
Divisor: 0
Not possible to Divide by zero
Number: 24
Divisor: 0
Not possible to Divide by zero
Number: 5
Divisor: 5
Quotient: 1
Number: 25
Index is Out of Range
Example:
public class InvalidAgeException : Exception
{
public InvalidAgeException(String message)
: base(message)
{
}
}
public class TestUserDefinedException
{
static void validate(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Sorry, Age must be greater than 18");
}
}
public static void Main(string[] args)
{
try
{
validate(12);
}
catch (InvalidAgeException e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
}
}
Output:
InvalidAgeException: Sorry, Age must be greater than 18
Rest of the code
C# Checked
The checked keyword is used to explicitly check overflow and conversion of integral type
values at compile time.
C# Checked Example
This program throws an exception and stops program execution.
using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
checked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}
Output:
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an o
C# Unchecked
The Unchecked keyword ignores the integral type arithmetic exceptions. It does not check
explicitly and produce result that may be truncated or wrong.
Example
using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
unchecked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}
Output:
-2147483647
Delegates Basics
In C#, we can also pass a method as a parameter to a different method using a delegate. We
use the delegate keyword to define a delegate.
A delegate is an object which refers to a method or you can say it is a reference type variable
that can hold a reference to the methods.
Types of Delegates
1. Single cast
2. Multicast
Declaration of Delegates
Delegate type can be declared using the delegate keyword. Once a delegate is declared,
delegate instance will refer and call those methods whose return type and parameter-list
matches with the delegate declaration.
Syntax:
[modifier] delegate [return_type] [delegate_name] ([parameter_list]);
Here, Name is the name of the delegate and it is taking parameter. Suppose we have a
delegate having int as the parameter.
Here, NewDelegate is a delegate which has two integers parameter x and y. It means that it
will take a method which also has two integers as its parameter and also integer return type.
So, it can take the method Add.
To create a new delegate, we either use the new keyword or simply decalare as we declare
variables.
using System;
class Test
{
public delegate int NewDelegate(int x, int y);
Console.WriteLine(d1(10, 20));
Console.WriteLine(d2(10, 20));
}
}
Delegates are similar to object references, but are used to reference methods instead of
objects. The type of a delegate is the type or signature of the method rather than the class.
Hence a delegate has three properties:
The type or signature of the method that the delegate can point to
The delegate reference which can be used to reference a method
The actual method referenced by the delegate
A delegate is a reference type derived from System.Delegate and its instances can be
used to call methods with matching signatures
A delegate is like a special kind of pointer in programming that can refer to a method
(function). You can use this delegate to call that method. So, it's a way to indirectly
refer to and execute methods with similar signatures (input and output types).
Delegate, the delegates can not be defined within a method (which is also true for
ordinary types). This is the reason why we have defined the delegate MyDelegate outside
the Main() method in the example code of this lesson.
class Test
{
delegate int MyDelegate(int p, int
q);static void Main()
{
MyDelegate arithMethod = null;
...
}
}
C# Multicast Delegate
In C#, a delegate can also point to multiple methods and is known as multicast delegate. We
use + and - operators to add and subtract methods from a delegate.
So, if d is a delegate, then we can add a method M to it using d = d+M or d += M. In this
case, invoking d will invoke all the methods in d sequentially.
Similarly, we can use - to remove methods from a delegate.
multicast delegates are sub-types of System.MulticastDelegate, which itself is a subclass of
System.Delegate.
The most important point to remember about multicast delegates is that "The return type of a
multicast delegate type must be void".
using System;
class Test
{
public delegate void NewDelegate();
d();
d = d-Display2;
d();
}
}
Events and Event Handling
Events are certain actions that happen during the execution of a program that the application
wishes to be notified about, so it can respond. An event can be a mouse click, a keystroke or
the coming of a certain time (alarm).
An event is basically a message which is said to be fired or triggered when the respective
action occurs.
A class that raises an event is called an 'event sender', a class that receives an event is called
and 'event consumer' and a method which is used to handle a particular event is called an
'event handler'.
Event Handling in C#
In .Net, events are implemented as multicast delegates.
In C# events are a first class (basic) language construct, and are defined using the event
keyword.
The steps for implementing events and event handling are:
1. Define a public delegate for the event outside any class boundary. The
conventional signature of a delegate for an event is:
public void EventDelegate(object sender, EventArgs e)
2. Define a class to generate or raise the event. Define a public event in the class
using the event keyword and the public delegate:
public event EventDelegate MyEvent
Write some logic to raise the event. When raising an event, the first argument is
usually the sender or originator of the event. The second argument is a sub-type of
System.EventArgs, which holds any additional data to be passed to the event
handler.
class SomeEventArgs : EventArgs
{
...
}
An event is generally raised like this:
SomeEventArgs someData = new SomeEventArgs(/*some necessary arguments*/);
MyEvent(this, someData);
Or if no data needs to be sent, the event is raised like this:
MyEvent(this, null);
3. Define a class to receive the events. This class is usually the main application class
containing the Main() method Write an event handler method in the class. The
signature of the event handler must be identical to that of the public delegate created
in step 1. The name of the event handler method conventionally starts with the word
"On", e.g.
public void OnMyEvent(object sender, EventArgs e)
{
// handle the event
}
Instantiate the event generator class created in step 2 like this:
EventClass eventObj = new EventClass();
Add the event handler written in the current class to the event generator class' event.
eventObj.MyEvent += new EventDelegate(OnMyEvent);
Now the event handler 'OnMyEvent()' will be called automatically whenever the event
'MyEvent' is triggered.
Multicast events
Since events are implemented as multicast delegates in C#, we can subscribe multiple
event handlers to a single event.
class Test
{
static void Main()
{
ClockTimer clockTimer = new
ClockTimer(); clockTimer.Timer += new
TimerEvent(OnClockTick);
clockTimer.Timer += new
TimerEvent(OnClockTick2);
clockTimer.Start();
}
public static void OnClockTick(object sender, EventArgs e)
{
Console.WriteLine("Received a clock tick event!");
}
public static void OnClockTick2(object sender, EventArgs e)
{
Console.WriteLine("Received a clock tick event in OnClockTick2!");
}
}
Here we have introduced another event handler, 'OnClockTick2', and have subscribed it
also to the Timer event in the Main() method using the '+=' operator.
Multithreading in C#
In the example above, Function1 and Function2 will run concurrently, each in its thread.
The order of execution is not determined by the order in which the threads are started. It’s
managed by the thread scheduler, which is part of the .NET runtime.
Thread Functionality
C# Thread class provides properties and methods to create and control threads. It is found in
System.Threading namespace.
C# Thread Properties
A list of important properties of Thread class are given below:
Property Description
C# Thread Methods
A list of important methods of Thread class are given below:
Method Description
We can call static and non-static methods on the execution of the thread. To call the static
and non-static methods, you need to pass method name in the constructor of ThreadStart
class. For static method, we don't need to create the instance of the class. You can refer it by
the name of class.
using System;
using System.Threading;
public class MyThread
{
public static void Thread1()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
}
public class ThreadExample
{
public static void Main()
{
Thread t1 = new Thread(new ThreadStart(MyThread.Thread1));
Thread t2 = new Thread(new ThreadStart(MyThread.Thread1));
t1.Start();
t2.Start();
}
}
Output:
The output of the above program can be anything because there is context switching between
the threads.
0
1
2
3
4
5
0
1
2
3
4
5
6
7
8
9
6
7
8
9
Let's see an example where we are executing different methods on each thread.
using System;
using System.Threading;
In C#, you can create and run multiple threads simultaneously to perform different tasks
concurrently. Sometimes, it is necessary to wait for one thread to complete before starting
another thread or wait for all threads to complete before proceeding further. To achieve
this, you can use the following methods to join threads in C#:
Thread.Join(): The Join method of the Thread class waits for the thread to complete its
execution before continuing with the execution of the calling thread. This method blocks the
calling thread until the target thread has completed its execution.
Example:
C#
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Thread t1 = new Thread(() =>
Console.WriteLine("Thread 1"));
Thread t2 = new Thread(() =>
Console.WriteLine("Thread 2"));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.WriteLine("Main Thread");
}
}
Output
Thread 1
Thread 2
Main Thread
Thread Synchronization
Synchronization is a technique that allows only one thread to access the resource for the
particular time. No other thread can interrupt until the assigned thread finishes its task.
C# Lock
We can use C# lock keyword to execute program synchronously. It is used to get lock for the
current thread, execute the task and then release the lock. It ensures that other thread does not
interrupt the execution until the execution finish.