C# Unit 5
C# Unit 5
C# Generics
Generic is a concept that allows us to define classes and methods with placeholder. C# compiler
replaces these placeholders with specified type at compile time. The concept of generics is used
to create general purpose classes and methods.
o define generic class, we must use angle <> brackets. The angle brackets are used to declare a
class or method as generic type. In the following example, we are creating generic class that can
be used to deal with any type of data.
Example
using System;
namespace CSharpProgram
{
class GenericClass<T>
{
public GenericClass(T msg)
{
Console.WriteLine(msg);
}
}
class Program
{
static void Main(string[] args)
{
GenericClass<string> gen = new GenericClass<string> ("This is generic class");
GenericClass<int> genI = new GenericClass<int>(101);
GenericClass<char> getCh = new GenericClass<char>('I');
}
}
}
Output:
C# allows us to create generic methods also. In the following example, we are creating generic
method that can be called by passing any type of argument.
Output:
C# Delegates
In C#, delegate is a reference to the method. It works like function pointer in C and C++. But it is
objected-oriented, secured and type-safe than function pointer.
For static method, delegate encapsulates method only. But for instance method, it encapsulates
method and instance both.
Internally a delegate declaration defines a class which is the derived class of System.Delegate.
Example
Let's see a simple example of delegate in C# which calls add() and mul() methods.
using System;
delegate int Calculator(int n);//declaring delegate
}
}
Output:
After c1 delegate, Number is: 120
After c2 delegate, Number is: 360
C# Reflection
C# Type class
C# Type class represents type declarations for class types, interface types, enumeration types,
array types, value types etc. It is found in System namespace. It inherits
System.Reflection.MemberInfo class.
C# Type Properties
Property Description
C# Type Methods
A list of important methods of Type class are given below:
Method Description
GetConstructors() Returns all the public constructors for the Type.
GetConstructors(BindingFlags) Returns all the constructors for the Type with specified
BindingFlags.
GetFields(BindingFlags) Returns all the public constructors for the Type with specified
BindingFlags.
GetMembers(BindingFlags) Returns all the members for the Type with specified BindingFlags.
GetMethods(BindingFlags) Returns all the methods for the Type with specified BindingFlags.
GetProperties(BindingFlags) Returns all the properties for the Type with specified BindingFlags.
Output:
System.Int32
Output:
Output:
System.String
System.Object
true
false
false
Output:
Output:
Output:
C# Multithreading
System.Threading Namespace
The System.Threading namespace contains classes and interfaces to provide the facility of
multithreaded programming. It also provides classes to synchronize the thread resource. A list of
commonly used classes are given below:
Thread
Mutex
Timer
Monitor
Semaphore
ThreadLocal
ThreadPool
Volatile etc.
Process and Thread
A process represents an application whereas a thread represents a module of the application.
Process is heavyweight component whereas thread is lightweight. A thread can be termed as
lightweight subprocess because it is executed inside a process.
Whenever you create a process, a separate memory area is occupied. But threads share a
common memory area.
Unstarted
Runnable (Ready to run)
Running
Not Runnable
Dead (Terminated)
Unstarted State
When the instance of Thread class is created, it is in unstarted state by default.
Runnable State
When start() method on the thread is called, it is in runnable or ready to run state.
Running State
Only one thread within a process can be executed at a time. At the time of execution, thread is in
running state.
Dead State
After completing the task, thread enters into dead or terminated state.
C# Thread class
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
IsAlive checks whether the current thread is alive or not. It is used to find the execution
status of the thread.
IsBackground is used to get or set value whether current thread is in background or not.
C# Thread Methods
Method Description
Join() is used to block all the calling threads until this thread terminates.
ResetAbort() is used to cancel the Abort request for the current thread.
Resume() is used to resume the suspended thread. It is obselete.
Sleep(Int32) is used to suspend the current thread for the specified milliseconds.
using System;
using System.Threading;
public class ThreadExample
{
public static void Main(string[] args)
{
Thread t = Thread.CurrentThread;
t.Name = "MainThread";
Console.WriteLine(t.Name);
}
}
Output:
MainThread
Thread Example: static method
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:
0
1
2
3
4
5
0
1
2
3
4
5
6
7
8
9
6
7
8
9
The output of the above program can be anything because there is context switching between the
threads.
using System;
using System.Threading;
public class MyThread
{
public void Thread1()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
}
public class ThreadExample
{
public static void Main()
{
MyThread mt = new MyThread();
Thread t1 = new Thread(new ThreadStart(mt.Thread1));
Thread t2 = new Thread(new ThreadStart(mt.Thread1));
t1.Start();
t2.Start();
}
}
Output:
0
1
2
3
4
5
0
1
2
3
4
5
6
7
8
9
6
7
8
9
Like above program output, the output of this program can be anything because there is context
switching between the threads.
using System;
using System.Threading;
Output:
task one
task two
using System;
using System.Threading;
public class MyThread
{
public void Thread1()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
Thread.Sleep(200);
}
}
}
public class ThreadExample
{
public static void Main()
{
MyThread mt = new MyThread();
Thread t1 = new Thread(new ThreadStart(mt.Thread1));
Thread t2 = new Thread(new ThreadStart(mt.Thread1));
t1.Start();
t2.Start();
}
}
Output:
4
4
Example
using System;
using System.Threading;
public class MyThread
{
public void Thread1()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
Thread.Sleep(200);
}
}
}
public class ThreadExample
{
public static void Main()
{
Console.WriteLine("Start of Main");
MyThread mt = new MyThread();
Thread t1 = new Thread(new ThreadStart(mt.Thread1));
Thread t2 = new Thread(new ThreadStart(mt.Thread1));
t1.Start();
t2.Start();
try
{
t1.Abort();
t2.Abort();
}
catch (ThreadAbortException tae)
{
Console.WriteLine(tae.ToString());
}
Console.WriteLine("End of Main");
}
}
Output:
Start of Main
0
End of Main
Naming Thread
You can change or get the name of the thread by using Name property of Thread class. Let's see
an example where we are setting and getting names of the threads.
using System;
using System.Threading;
Output:
Player1 is running
Player2 is running
Player3 is running
ThreadPriority
In C# Programming Language, each and every thread has a priority that determines how often
the thread gets access to the CPU. In general, a Low-Priority Thread will get less CPU time than
a High-Priority Thread. The important point that we need to understand is how much CPU time a
thread will get, it doesn’t only depend on its priority, but also depends on the kind of operation it
is performing.
Let's see an example where we are changing the priority of the thread. The high priority thread
can be executed first. But it is not guaranteed because thread is highly system dependent. It
increases the chance of the high priority thread to execute before low priority thread.
Example
using System;
using System.Threading;
public class MyThread
{
public void Thread1()
{
Thread t = Thread.CurrentThread;
Console.WriteLine(t.Name+" is running");
}
}
public class ThreadExample
{
public static void Main()
{
MyThread mt = new MyThread();
Thread t1 = new Thread(new ThreadStart(mt.Thread1));
Thread t2 = new Thread(new ThreadStart(mt.Thread1));
Thread t3 = new Thread(new ThreadStart(mt.Thread1));
t1.Name = "Player1";
t2.Name = "Player2";
t3.Name = "Player3";
t3.Priority = ThreadPriority.Highest;
t2.Priority = ThreadPriority.Normal;
t1.Priority = ThreadPriority.Lowest;
t1.Start();
t2.Start();
t3.Start();
}
}
Output:
The output is unpredictable because threads are highly system dependent. It may follow any
algorithm preemptive or non-preemptive.
Player1 is running
Player3 is running
Player2 is running
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.
In multithreading program, threads are allowed to access any resource for the required execution
time. Threads share resources and executes asynchronously. Accessing shared resources (data) is
critical task that sometimes may halt the system. We deal with it by making threads
synchronized.
It is mainly used in case of transactions like deposit, withdraw etc.
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.
Here, we are creating two examples that executes asynchronously and synchronously.
Output:
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
Web Services in C#
Web Service is known as the software program. These services use the XML to exchange the
information with the other software with the help of the common internet Protocols. In the
simple term, we use the Web Service to interact with the objects over the internet.