How to check what is in SQL Server plan cache

To see what is in SQL Server plan cache we will make use of the following 3 dynamic management views and functions provided by sql server

1. sys.dm_exec_cached_plans
2. sys.dm_exec_sql_text
3. sys.dm_exec_query_plan


Use the following query to see what is in the plan cache

SELECT cp.usecounts, cp.cacheobjtype, cp.objtype, st.text, qp.query_plan
FROM sys.dm_exec_cached_plans AS cp
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp
ORDER BY cp.usecounts DESC

To remove all elements from the plan cache use the following command
DBCC FREEPROCCACHE

Open transactions with text and plans


Here’s a little script that tells who has open transactions on the server – not just the single oldest active transaction that DBCC OPENTRAN returns.

It gives back:

  • session ID
  • login name
  • database context
  • transaction begin time
  • how many log records have been generated by the transaction
  • how much log space has been taken up by those log records
  • how much log space has been reserved in case the transaction rolls back
  • the last T-SQL that was executed in the context of the transaction
  • the last query plan that was executed (only for currently executing plans)

SELECT
    [s_tst].[session_id],
    [s_es].[login_name] AS [Login Name],
    DB_NAME (s_tdt.database_id) AS [Database],
    [s_tdt].[database_transaction_begin_time] AS [Begin Time],
    [s_tdt].[database_transaction_log_bytes_used] AS [Log Bytes],
    [s_tdt].[database_transaction_log_bytes_reserved] AS [Log Rsvd],
    [s_est].text AS [Last T-SQL Text],
    [s_eqp].[query_plan] AS [Last Plan]
FROM
    sys.dm_tran_database_transactions [s_tdt]
JOIN
    sys.dm_tran_session_transactions [s_tst]
ON
    [s_tst].[transaction_id] = [s_tdt].[transaction_id]
JOIN
    sys.[dm_exec_sessions] [s_es]
ON
    [s_es].[session_id] = [s_tst].[session_id]
JOIN
    sys.dm_exec_connections [s_ec]
ON
    [s_ec].[session_id] = [s_tst].[session_id]
LEFT OUTER JOIN
    sys.dm_exec_requests [s_er]
ON
    [s_er].[session_id] = [s_tst].[session_id]
CROSS APPLY
    sys.dm_exec_sql_text ([s_ec].[most_recent_sql_handle]) AS [s_est]
OUTER APPLY
    sys.dm_exec_query_plan ([s_er].[plan_handle]) AS [s_eqp]
ORDER BY
    [Begin Time] ASC;
GO

List generic collection class in C#

  • List is a generic collection class which stores strongly typed objects into it.
  • List is an index based collection of object.
  • It provides methods to search, sort, Manipulate the lists of objects.
  • List is generic version of an ArrayList class.
  • List size can be increased or decreased as per requirement.

See below example of using List class

+
Code
using System;
using System.Collections.Generic;
 
namespace List_Generic_Class
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> lstEmployee = new List<Employee>();
 
            Employee emp1 = new Employee() { empId = 111, empName = "Sam" };
            Employee emp2 = new Employee() { empId = 112, empName = "Jane" };
            Employee emp3 = new Employee() { empId = 113, empName = "Sachin" };
            Employee emp4 = new Employee() { empId = 114, empName = "Jack" };
 
            //Add function
            lstEmployee.Add(emp1);
            lstEmployee.Add(emp2);
            lstEmployee.Add(emp3);
            lstEmployee.Add(emp4);
 
            Console.WriteLine("Retrieving Employees from List\n");
            foreach (Employee emp in lstEmployee)
            {
                Console.WriteLine("Employee Id : {0} \t Employee Name: {1}",emp.empId,emp.empName);
            }
 
            //Remove function
            lstEmployee.Remove(emp1);
 
            Console.WriteLine("\nRetrieving Employees from List after removing employee with Id 111\n");
            foreach (Employee emp in lstEmployee)
            {
                Console.WriteLine("Employee Id : {0} \t Employee Name: {1}", emp.empId, emp.empName);
            }
 
            Employee emp5 = new Employee() { empId = 115, empName = "Jim" };
 
            //Insert function
            lstEmployee.Insert(2,emp5);
 
            Console.WriteLine("\nRetrieving Employees from List after Adding new Employee at specified location\n");
            foreach (Employee emp in lstEmployee)
            {
                Console.WriteLine("Employee Id : {0} \t Employee Name: {1}", emp.empId, emp.empName);
            }
 
            Console.ReadLine();
        }
    }
 
    public class Employee
    {
        public int empId { getset; }
        public string empName { getset; }
    }
}

In the above code sample, we have created object of List class lstEmployee. We also created Employee class and adding several objects of employee class into the list. Below are some basic methods of List class that we have used in above code.

Add : This method adds an object into the list. It expects object of type T as parameter. In above sample we are adding several objects of Employee type.

Remove : This method removes the specified object from the list. It also expect object of type T to remove.

Insert : This method insert an object into the list at specified index. This method expects index as 1st parameter and object of type T to insert at that index. If we add objects in between, then the subsequent index after that gets incremented by one. If you see in above code sample, we have added employee object with name Jim at index no 2, thus index of subsequent object with name jack gets incremented by 1.

Below is the output of above program.

List generic collection class in c#

Dictionary Generic collection class in C#

  • Dictionary class in C# is a generic type which stores objects in a Key-Value format.
  • We can store objects of TValue type as value with TKey type as its Key.
  • Retrieval of value using key is very fast.
  • Every key in dictionary must be unique.
  • A Key cannot be null, but a value can be null, if a type of value is reference type.
  • While enumerating dictionary elements using foreach loop, each element in the dictionary is treated as a KeyValuePair<Tkey,Tvalue> representing a value and its key.
See below code of Using Dictionary class with its basic functions.

+
Code
using System;
using System.Collections.Generic;
 
namespace Dictionary_generic_class
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<intstring> dictEmployees = new Dictionary<intstring>();
 
            Employee emp1 = new Employee() { empId = 111, empName = "Sam" };
            Employee emp2 = new Employee() { empId = 112, empName = "Jane" };
            Employee emp3 = new Employee() { empId = 113, empName = "Sachin" };
            Employee emp4 = new Employee() { empId = 114, empName = "Jack" };
 
            //Add function
            dictEmployees.Add(emp1.empId, emp1.empName);
            dictEmployees.Add(emp2.empId, emp2.empName);
            dictEmployees.Add(emp3.empId, emp3.empName);
            dictEmployees.Add(emp4.empId, emp4.empName);
 
            Console.WriteLine("Looping through dictionary\n");
 
            foreach (KeyValuePair<intstring> kvp in dictEmployees)
            {
                Console.WriteLine("Employee Id:{0}\t\tEmployee Name:{1}",kvp.Key,kvp.Value);
            }
 
            //Remove function
            dictEmployees.Remove(1115);
 
            Console.WriteLine("\nAfter removing element with key 111\n");
 
            foreach (KeyValuePair<intstring> kvp in dictEmployees)
            {
                Console.WriteLine("Employee Id:{0}\t\tEmployee Name:{1}", kvp.Key, kvp.Value);
            }
 
            //TryGetValue function
            string EmployeeWithId = "N/A";
            dictEmployees.TryGetValue(115, out EmployeeWithId);
 
            Console.WriteLine("\nEmployee Name with Id 115 is {0}", EmployeeWithId);
 
            dictEmployees.TryGetValue(112, out EmployeeWithId);
 
            Console.WriteLine("\nEmployee Name with Id 112 is {0}", EmployeeWithId);
 
            //ContainsKey and ContainsValue function
            if (dictEmployees.ContainsKey(113))
                Console.WriteLine("\nEmployee with Id 113 present");
            else
                Console.WriteLine("\nEmployee with Id 113 not present");
 
            if (dictEmployees.ContainsValue("Jack"))
                Console.WriteLine("\nEmployee Jack present");
            else
                Console.WriteLine("\nEmployee Jack not present");
           
            Console.ReadLine();
        }
    }
 
 
    public class Employee
    {
        public int empId { getset; }
        public string empName { getset; }
    }
}

In above code sample, we have created Dictionary class object dictEmployees with key as integer and value as string. We are storing several Employee objects into the dictionary with key as EmpId and value as EmpName.
Below are the basic methods of dictionary, with their use, that we used in our code sample.

Add : This method is used to add object with Key and value of type Tkey and TValue.

Remove : This method removes element from dictionary with specified Key which is passed as parameter for this function.

TryGetValue : This method checks if the provided key as first parameter is present in the dictionary or not. If present. then it outputs corresponding value to a string variable that we passed as a second parameter to this function. If no value is present corresponding to that key then by default it will assign a default value.

ContainsKey/ContainsValue : This method check if a specified Key/Value present in the dictionary or not.

Below is the output of above code:

Dictionary generic class in c#

Stack class in C#

  • Stack class object stores elements in Last In First Out(LIFO) manner, i.e. Element that gets added last into the stack will get removed first from the stack.
  • Element gets added from and removed from same end.
  • Use stack when you want to access element in the reverse order that they are stored in the collection. 
  • Use stack if you want to discard the element as soon as you retrieve it.
See below example of using stack with its main functions.

+
Code
using System;
using System.Collections;
 
namespace Stack_Collection
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack stkEmp = new Stack();
 
            Employee emp1 = new Employee() { empId = 111, empName = "Sam" };
            Employee emp2 = new Employee() { empId = 112, empName = "Jane" };
            Employee emp3 = new Employee() { empId = 113, empName = "Sachin" };
            Employee emp4 = new Employee() { empId = 114, empName = "Jack" };
 
            stkEmp.Push(emp1);
            stkEmp.Push(emp2);
            stkEmp.Push(emp3);
            stkEmp.Push(emp4);
 
            Console.WriteLine("Retrieving elements from Stack\n");
 
            while (stkEmp.Count > 0)
            {
                Console.WriteLine("Employee Id: {0} information", ((Employee)stkEmp.Peek()).empId);
                Employee emp = (Employee)stkEmp.Pop();
                Console.WriteLine("Emplopyee Id : {0} \t Employee Name : {1}", emp.empId, emp.empName);
                Console.WriteLine("Elements in Stack are:{0}\n", stkEmp.Count);
            }
 
            Console.ReadLine();
        }
 
    }
 
    public class Employee
    {
        public int empId { getset; }
        public string empName { getset; }
    }
}

In the above code sample, We have created a class called Employee with 2 Properties empId, empName.
We have created a Stack class object stkEmp and storing few Employee objects in it. Below are the main functions of Stack that we used in our above code.

Push: Add the element at the begining of Stack.
Pop : Retrieve and remove the top element from the Stack.
Peek : Peek function retrieves top element from the stack but it does not remove it.

Below is the output of above program



If you see the output above, The element that gets added last in stack will get retrieved and removed first when we use Pop method of stack. 

Queue class in C#

  • Queue class is a circular array that stores elements in First In First Out(FIFO) manner, i.e. Element that gets added first into the queue will get removed first from the queue.
  • Element gets added from one end and removed from other end.
  • Use queue when you want to access element in the same order that it is stored in the collection. 
  • Use Queue if you want to discard the element as soon as you retrieve it.

See below example of using queue with its main functions.

+
Code
using System;
using System.Collections;
 
namespace Queue_Collection_Class
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue qEmp = new Queue();
 
            Employee emp1 = new Employee() { empId = 111, empName = "Sam" };
            Employee emp2 = new Employee() { empId = 112, empName = "Jane" };
            Employee emp3 = new Employee() { empId = 113, empName = "Sachin" };
            Employee emp4 = new Employee() { empId = 114, empName = "Jack" };
 
            qEmp.Enqueue(emp1);
            qEmp.Enqueue(emp2);
            qEmp.Enqueue(emp3);
            qEmp.Enqueue(emp4);
 
            Console.WriteLine("Retrieving elements from Queue\n");
 
            while (qEmp.Count>0)
            {
                Console.WriteLine("Employee Id: {0} information", ((Employee)qEmp.Peek()).empId);
                Employee emp = (Employee)qEmp.Dequeue();
                Console.WriteLine("Emplopyee Id : {0} \t Employee Name : {1}", emp.empId,emp.empName);
                Console.WriteLine("Elements in Queue are:{0}\n",qEmp.Count);
            }
 
            Console.ReadLine();
        }
    }
 
    public class Employee
    {
        public int empId { getset; }
        public string empName { getset; }
    }
}

In the above code sample, We have created a class called Employee with 2 Properties empId, empName.
We have created a Queue class object qEmp and storing few Employee objects in it. Below are the main functions of Queue that we used in our above code.

Enqueue : Add the element at the end of of Queue.
Dequeue : Retrieve and remove the first element from the Queue.
Peek : Peek function retrieves first element from the Queue but it does not remove it.

Below is the output of above program

Queue in C#

ArrayList in C#

  • ArrayList is an index based ordered collection of objects.
  • It is like array, but like array its size is not fixed. It can dynamically grows or shrinks as per the requirement.
  • We can add as many Items as possible into arraylist till the memory is available.
  • As compared to Array, ArrayList is not type safe. Also it stores the objects into it, it is an overhead of boxing and unboxing of objects while adding,accessing items from ArrayList.

See below simple example of using ArrayList

+
Code
using System;
using System.Collections;
 
namespace Arraylist_Collection
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arrlst = new ArrayList();
            
            arrlst.Add(1);
            arrlst.Add(2);
            arrlst.Add("one");
            arrlst.Add("two");
 
            foreach (object obj in arrlst)
            {
                Console.WriteLine(obj);
            }
            Console.ReadLine();
        }
    }
}

In above example, We have declared an ArrayList arrlst. By using Add method of ArrayList which requires object as a parameter, we added elements into it. We have added both integer elements and string elements into it. We accessed the elements of ArrayList using ForEach loop. We can use For loop as well for accessing the elements from ArrayList.
As we seen in above example, At a time we can store any object in ArrayList (in our case we stored Integer and String Item into ArrayList), It is not type safe.

See below example for now, where we have declared variable m of integer type in foreach loop to assign integer value from Arraylist to it and wrote this for loop in the try..catch block in order to capture error.
If you check the output below,  you will see the error Specified cast is not valid. after printing 'one'. There is a type cast error occurred while converting the string value 'one' into integer. This example indicates that ArrayList is not type safe as we store any object in it.

+
Code
using System;
using System.Collections;
 
namespace Arraylist_Collection
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arrlst = new ArrayList();
            
            arrlst.Add(1);
            arrlst.Add(2);
            arrlst.Add("one");
            arrlst.Add("two");
 
            try
            {
                foreach (object obj in arrlst)
                {
                    Console.WriteLine(obj);
                    int m = (int)obj;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
    }
}

ArrayList in C#

See below example with use of some basic and important functions of ArrayList.

+
Code
using System;
using System.Collections;
 
namespace Arraylist_Collection
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arrUserList = new ArrayList();
 
            //Add function
            arrUserList.Add("Sameer");
            arrUserList.Add("Yuvraj");
            arrUserList.Add("Ramesh");
            arrUserList.Add("Amit");
            arrUserList.Add("Suresh");
 
            Console.WriteLine("Added users using Add\n");
            foreach (object obj in arrUserList)
            {
                Console.WriteLine(obj);
            }
 
            //AddRange Function
            string[] strUserList = { "Satish""Babita" };
 
            arrUserList.AddRange(strUserList);
 
            Console.WriteLine("\nAdded users using AddRange\n");
            foreach (object obj in arrUserList)
            {
                Console.WriteLine(obj);
            }
 
            //Count Function
            Console.WriteLine("\nCount of Elements of arraylist\n");
            Console.WriteLine("No of Elements : {0}", arrUserList.Count);
 
            //Remove function
            arrUserList.Remove("Babita");
 
            Console.WriteLine("\nRemoved perticular user using Remove function\n");
            foreach (object obj in arrUserList)
            {
                Console.WriteLine(obj);
            }
 
            //RemoveAt function
            arrUserList.RemoveAt(0);
 
            Console.WriteLine("\nRemoved user using RemoveAt function\n");
            foreach (object obj in arrUserList)
            {
                Console.WriteLine(obj);
            }
 
            //Contains Function
            Console.WriteLine("\nCheck if element exists or not using Contains function");
            if (arrUserList.Contains("Amitabh"))
                Console.WriteLine("Amitabh is in ArrayList");
            else
                Console.WriteLine("Amitabh is not in ArrayList");
 
            //Sort Function
            arrUserList.Sort();
 
            Console.WriteLine("\nArrayList after sorting\n");
            foreach (object obj in arrUserList)
            {
                Console.WriteLine(obj);
            }
 
            //Reverse Function
            arrUserList.Reverse();
 
            Console.WriteLine("\nArrayList after reversing\n");
            foreach (object obj in arrUserList)
            {
                Console.WriteLine(obj);
            }
 
            Console.ReadLine();
        }
    }
} 
 
 

Add : Adds the element at the last index of ArrayList
AddRange: This function Accepts any collection that implements ICollection Interface and adds the element at the end of Arraylist.
Count: Returns the number of Elements. 
Remove: Remove specified Item from ArrayList
RemoveAt: Remove Item located at specified Index.
Contains: Determine whether Specified Item present in ArrayList or not. Return true if present otherwise false.
Sort: Sort elements in the Ascending order.
Reverse: Reverse the order of Elements.


Below is the output of above program.

ArrayList in C# second example

HashTable in C#

  • Hashtable stores elements in a Key/Value pair format and the elements are organized based on the hash code of the key.
  • In a Key/Value pair, Key should not be null, but a value can be null. Also Key should be unique, but value can be duplicate.
  • The Objects used as key are required to override GetHashCode and Equals methods of base class Object.
  • Like ArrayList, HashTable also have overhead of boxing and unboxing of objects while adding or accessing elements from HashTable.

See below example of using HashTable.

+
Code
using System;
using System.Collections;
 
namespace HashTable_Collection
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp1 = new Employee() { empId = 111,empName="Sam"};
            Employee emp2 = new Employee() { empId = 112, empName = "Jane" };
            Employee emp3 = new Employee() { empId = 113, empName = "Sachin" };
            Employee emp4 = new Employee() { empId = 114, empName = "Jack" };
 
            Hashtable hashTblEmployee = new Hashtable();
            hashTblEmployee.Add(emp1.empId, emp1.empName);
            hashTblEmployee.Add(emp2.empId, emp2.empName);
            hashTblEmployee.Add(emp3.empId, emp3.empName);
            hashTblEmployee.Add(emp4.empId, emp4.empName);
 
            foreach (DictionaryEntry kp in hashTblEmployee)
            {
                Console.WriteLine(kp.Key + "\t" + kp.Value);
            }
            Console.ReadLine();
        }
    }
 
    public class Employee
    {
        public int empId { getset; }
        public string empName { getset; }
    }
}

In above code sample, we have created a class employee with fields empId and empName. We are storing several Employee objects in a HashTable with Key as empId and value as empName.

We have declared HashTable object hashTblEmployee and added Employee objects into it using add method which requires 2 parameters, one is Key object and second one is Value Object.

We are now retrieving each HashTable Key and Value using foreach loop. While retrieving elements from HashTable, it returns DictionaryEntry object which contains Key and Value properties corresponds to Key and Value of each hashTable element. Using this DictionaryEntry object we get Key and its corresponding Value from HashTable.

Below is a sample code for HashTable with basic and important functions.

+
Code
using System;
using System.Collections;
 
namespace HashTable_Collection
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp1 = new Employee() { empId = 111, empName = "Sam" };
            Employee emp2 = new Employee() { empId = 112, empName = "Jane" };
            Employee emp3 = new Employee() { empId = 113, empName = "Sachin" };
            Employee emp4 = new Employee() { empId = 114, empName = "Jack" };
 
            Hashtable hashTblEmployee = new Hashtable();
 
            //Add function
            hashTblEmployee.Add(emp1.empId, emp1.empName);
            hashTblEmployee.Add(emp2.empId, emp2.empName);
            hashTblEmployee.Add(emp3.empId, emp3.empName);
            hashTblEmployee.Add(emp4.empId, emp4.empName);
 
            foreach (DictionaryEntry kp in hashTblEmployee)
            {
                Console.WriteLine(kp.Key + "\t" + kp.Value);
            }
 
            Console.WriteLine("\n");
 
            //Count function
            Console.WriteLine("Number of elements in HashTable = {0}", hashTblEmployee.Count);
            Console.WriteLine("\n");
 
            //Contains/ContainsKey function
            Employee emp5 = new Employee() { empId = 111, empName = "Jim" };
 
            if (!hashTblEmployee.Contains(emp5.empId))
            {
                hashTblEmployee.Add(emp5.empId, emp5.empName);
                foreach (DictionaryEntry kp in hashTblEmployee)
                {
                    Console.WriteLine(kp.Key + "\t" + kp.Value);
                }
            }
            else
            {
                Console.WriteLine("Element with Key {0} already exists", emp5.empId);
            }
 
            //ContainsValue function
            if (hashTblEmployee.ContainsValue("Emma"))
            {
                Console.WriteLine("Emma is present in HashTable");
            }
            else
            {
                Console.WriteLine("Emmma is not present in HashTable");
            }
 
            //Remove function
            hashTblEmployee.Remove(111);
 
            Console.WriteLine("\nRemoving Element with key 111");
            foreach (DictionaryEntry kp in hashTblEmployee)
            {
                Console.WriteLine(kp.Key + "\t" + kp.Value);
            }
 
            Console.ReadLine();
        }
    }
 
    public class Employee
    {
        public int empId { getset; }
        public string empName { getset; }
    }
}

Add : Adds the element into HashTable. It requires 2 parameters, Key object and Value object.
Count: Returns the number of Elements.
Contains/ContainsKey : Determine whether specified Key is present in HashTable or not. Return true if present otherwise false. Contains function internally calls ContainsKey function. So you can use either Contains function or ContainsKey function, both will give you same result.
ContainsValue : Determine whether specified Value is present in HashTable or not. Return true if present otherwise false.
Remove: Remove specified Item from HashTable. Expect Key object to remove as parameter.

Below is the output of above program.

HashTable in C#

Reflection in C#.Net

You should have Knowledge of assemblies (dll or exe) before continuing this Topic.
  • Reflection in dot net is used to inspects assemblies(dll or exe) metadata at runtime.
  • By using reflection we can get all the details of the types(Classes, Interfaces, Stuctures) declared in an assembly and also we can dynamically invokes methods from these assemblies's types.
  • As you know dot net framework is a collection of various assemblies, We can access metadata of these assemblies in our code at runtime.
One of real life example of using reflection is the Dot Net Integrated Development Environment (IDE),  Where while doing windows or web application, when you drag a button or any other control (These controls are nothing but the Classes defined in assemblies(dll) in the dot net framework) on to your Form/Page, you can see various Properties/Events of that control on right side(by default). Those properties/Events gets displayed using reflection.

Lets see example of using reflection below.

+
Code
using System;
using System.Reflection;
 
namespace Reflection_examples
{
    class Program
    {
        static void Main(string[] args)
        {
            string TypeName = "Reflection_examples.classForReflectionEx";
            Type T = Type.GetType(TypeName);
 
            //Get proprties from class classForReflectionEx
            PropertyInfo[] propInfo = T.GetProperties();
            Console.WriteLine("Properties present in {0}", T.Name);
 
            foreach (PropertyInfo pInfo in propInfo)
            {
                Console.WriteLine("\n\t{0}.{1}", pInfo.DeclaringType.Name, pInfo.Name);
            }
 
            //Get all Methods from class classForReflectionEx
            MethodInfo[] methodInfo = T.GetMethods();
            Console.WriteLine("\nMethods present in {0}", T.Name);
 
            foreach (MethodInfo mInfo in methodInfo)
            {
                Console.WriteLine("\n\t {0} {1}.{2}", mInfo.ReturnType.ToString(),mInfo.DeclaringType.Name, mInfo.Name);
            }
 
            Console.ReadLine();
        }
    }
 
 
    public class classForReflectionEx
    {
        public int id { getset; }
        public string name { getset; }
 
        public void function1()
        {
            Console.WriteLine("Welcome to Function1");
        }
 
        public void function2()
        {
            Console.WriteLine("Welcome to Function2");
        }
    }
}

for using reflection you have to include System.Reflection namespace in your application.
In the above example, We have created a class named classForReflectionEx. Let us consider this class is present in some other assembly. Now see the code in the main method of Program class, where we used a Type class and passed the Type name(In above case we need information of class classForReflectionEx) whose information we want to getType method of  the Type class.

Now by using PropertiesInfo class, which is present in System.Reflection namespace, we get all the properties that are present in the type (in above case class classForReflectionEx). By using DeclaringType.Name we get the name of type where we declared that property.
Similarly, for getting method details, we use MethodInfo class.

Below is the output of above Sample program.

Reflection example in C#.Net

If you check the output above, you can see below methods are also there in output other than the two methods function1 and function2 that we declared in our class classForReflectionEx. When our class gets compiled that time internally our properties gets converted to get_id,set_id method and get_name and set_name method, hence these methods are reflecting in our output.

Other than these methods we have four additional methods. These methods are present in dot net base class System.Object and we all know that every type(class) in dot net gets inherited from System.Object class and hense we have these four methods for our declared class.

System.Int32 classForReflectionEx.get_id
System.Void classForReflectionEx.set_id
System.String classForReflectionEx.get_name
System.Void classForReflectionEx.set_name
System.String Object.ToString
System.Boolean Object.Equals
System.Int32 Object.GetHashCode
System.Type Object.GetType

You can take this example and try out to get the other members for the class.

What is Delegate? What is the use of Delegate?

  • Delegate is type that references to a method that has signature and parameter type same as delegate signature and parameter type.
  • Delegates are type safe function pointer.
  • Delegate declaration is same like a method declaration but without the body. 
  • Delegates allow functions to be passed as parameter to other functions.
  • using delegate keyword we can declare delegate type in C#.

See below example of delegate.

+
Code

using System;
 
namespace delegateSample
{
    public delegate float delCalculate(float a, float b);
 
    class Program
    {
        static void Main(string[] args)
        {
            float num1 = 10,num2 = 20;
 
            delCalculate delCalci = new delCalculate(delegateMethodDeclaration.add);
            delCalculate delCalci1 = new delCalculate(delegateMethodDeclaration.multiply);
 
            Console.WriteLine("Addition of 2 numbers = {0}", delCalci(num1,num2));
            Console.WriteLine("Multiplication of 2 numbers = {0}", delCalci1(num1, num2));
            Console.ReadLine();
        }
    }
 
    //New class declared
    public class delegateMethodDeclaration
    {
        public static float add (float firstNum,float secondNum)
        {
            return firstNum + secondNum;
        }
 
        public static float multiply(float firstNum,float secondNum)
        {
            return firstNum * secondNum;
        }
    }
}

We have declared delegate delCalculate with 2 float parameter and return type as float. So whatever function this delegate references should have 2 float parameters and its return type should be float. If we try to reference a function with diferent type of parameter and return type by using this delegate, then it will give compile time error. This shows that delegates are type safe function pointer.
In above sample we have 2 method declared with 2 float parameter and return type as float in delegateMethodDeclaration class and referenced and invoked these methods by using delegate object(Same like a class) in main method.

Now, you are wondering why we used delegate to call a method? We can directly call this method. Lets see what is the actual use of delegate by having some examples without using delegate and using delegate below.

Let us consider below simple example, where we have declared a class Numbers and a method called getAverage() which return average of all the numbers that we passed to it. Let us consider this Numbers class is in another assembly(dll) and we are using this dll in our program and calling function getAverage() in our main program (see below Code 1, I have called this method in our program class's main method.).


Code 1

+
Code
using System;
 
namespace withoutUsingDelegate
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] i = { 100, 5, 6, 7, 3, 1, 9, 8, 12, 13, 16, 17 };
            Numbers num = new Numbers(i);
            Console.WriteLine("Average of all numbers = {0}", num.getAverage(i));
            Console.ReadLine();
        }
    }
 
 
    //Number class created
    public class Numbers
    {
        int[] _numArr;
 
        public Numbers(int[] numArr)
        {
            _numArr = numArr;
        }
 
        public float getAverage(int[] numArr)
        {
            float total = 0;
            for (int i = 0; i < numArr.Length; i++)
            {
                total = total + numArr[i];
            }
            return total / numArr.Length;
        }
 
    }
 
}


Code 2

+
Code
using System;
 
namespace withoutUsingDelegate
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] i = { 100, 5, 6, 7, 3, 1, 9, 8, 12, 13, 16, 17 };
            Numbers num = new Numbers(i);
            Console.WriteLine("Average of all numbers = {0}", num.getAverage(i));
            Console.WriteLine("Average of all even numbers = {0}", num.getAverageOfEvenNumbers(i));
            Console.ReadLine();
        }
    }
 
 
    //Number class created
    public class Numbers
    {
        int[] _numArr;
 
        public Numbers(int[] numArr)
        {
            _numArr = numArr;
        }
 
        public float getAverage(int[] numArr)
        {
            float total = 0;
            for (int i = 0; i < numArr.Length; i++)
            {
                total = total + numArr[i];
            }
            return total / numArr.Length;
        }
 
        public float getAverageOfEvenNumbers(int[] numArr)
        {
 
            float total = 0;
            int evenNumbers = 0;
            for (int i = 0; i < numArr.Length; i++)
            {
                if (numArr[i] % 2 == 0)
                {
                    evenNumbers = evenNumbers + 1;
                    total = total + numArr[i];
                }
            }
            return total / evenNumbers;
        }
    }
}


Now suppose I want to calculate average of only even numbers from all the numbers that I passed. In order to do that I need to make change in my Numbers class. I can write a different function for that in my Numbers class or I will modify getAverage() function (See Code 2). But I want to make my Numbers class to be reusable. So instead of making changes in my Numbers class, I want users let implement logic from their end to do the functionality as per their requirement and pass it to my reusable function in Numbers class and here is actual delegate get comes into picture.

See the below example by using delegate for calculating average of all numbers and Even numbers.
 

+
Code
using System;
 
namespace Delegate_usage
{
    public delegate float delegategetAverage(int[] numbers);
    class Program
    {
        static void Main(string[] args)
        {
            int[] i = {100,5,6,7,3,1,9,8,12,13,16,17};
            Numbers num = new Numbers(i);
 
            delegategetAverage avgOfAllNum = new delegategetAverage(getAverage);
            Console.WriteLine("Average of All numbers = {0}", num.getAverageOfNum(avgOfAllNum));
 
            //calculating average of even numbers 
            delegategetAverage avgOfEvenNum = new delegategetAverage(getAverageOfEvenNumbers);
            Console.WriteLine("Average of Even numbers = {0}", num.getAverageOfNum(getAverageOfEvenNumbers));
            Console.ReadLine();
        }
 
        public static float getAverage(int [] numArr)
        {
            float total = 0;
            for (int i = 0; i < numArr.Length; i++)
            {
                total = total + numArr[i];
            }
            return total / numArr.Length;
        }
 
        public static float getAverageOfEvenNumbers(int [] numArr)
        {
            float total = 0;
            int evenNumbers = 0;
            for (int i = 0; i < numArr.Length; i++)
            {
                if (numArr[i] % 2 == 0)
                {
                    evenNumbers = evenNumbers + 1;
                    total = total + numArr[i];
                }
            }
            return total / evenNumbers;
        }
       
    }
 
    //Number class created
    public class Numbers
    {
        int[] _numArr;
 
        public Numbers(int[] numArr)
        {
            _numArr = numArr;
        }
 
        public float getAverageOfNum(delegategetAverage delAvg)
        {
            return delAvg(_numArr);
        }
    }
}

In the above example we have declared method getAverageOfNum() in our Numbers class which accept delegate as parameter. If a user want to calculate average of all the numbers then he simply create a method from their end which matches with delegate signatures. See in above example when I want to calculate average of all the numbers, I have created one function getAverage() at my side(client side) and passed this function to getAverageOfNum() as parameter with the help of delegate. Lets user of that class decide what functionality he want.

Similarly, when I want to calculate the average of even numbers then I have simply written and passed a function getAverageOfEvenNumbers() from my side using second delegate instance avgOfEvenNum. 
No need to make changes in our Numbers class.

Similarly, If you want to calculate the average of odd numbers, you can define the function at your end and pass it as parameter to function in Numbers class using another delegate instance.

This is one of simple example of delegate. If you check LINQ functions in dot net framework, you can see in most functions have heavy use of delegates. We will discuss more about LINQ in later chapter.