Delegate in C#

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked

so A function can have one or more parameters of different data types, but what if you want to pass a function itself as a parameter? How does C# handle the callback functions or event handler? The answer is - delegate.

A delegate can be declared using delegate keyword followed by a function signature as shown below.

Syntax:

<access modifier> delegate <return type> <delegate_name>(<parameters>)

Syntax Example

public delegate void Print(int value);


Example

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
  // Declaration
  public delegate void SimpleDelegate();
  class TestDelegate
  {
    public static void MyFunc()
    {
      Console.WriteLine("Hi , Nitin kumar, I am MyFunc() function and i was called by delegate ...");
    }
    public static void Main()
    {
      // Instantiation
      SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);
      // Invocation
      simpleDelegate();
      Console.Read();
    }
  }
}





















 OutPut :


Common and Useful SQL Server Quries



-----------------Get List of All Databases (DB)--------------------
 EXEC sp_helpdb


-----------------Get procedure text ----------------------------------

exec sp_helptext @objname = 'BeneficiaryEnrolmentDataStatusSave'



---------------- Recompile stored procedure ---------------------

EXEC sp_recompile'BeneficiaryEnrolmentDataStatusSave';
 GO


----------------Recompile all stored procedure on table---------

 EXEC sp_recompile N'txncustomers';
GO


----------------Get all columns of a specific data type-----------

SELECT OBJECT_NAME(c.OBJECT_ID) as Table_Name, c.name as Column_Name FROM sys.columns AS c JOIN sys.types AS t ON c.user_type_id=t.user_type_id WHERE t.name = 'varchar'  --G



---------------Get all Nullable columns of a table----------------
SELECT OBJECT_NAME(c.OBJECT_ID) as Table_Name, c.name as Column_Name FROM sys.columns AS c JOIN sys.types AS t ON c.user_type_id=t.user_type_id WHERE c.is_nullable=0 AND OBJECT_NAME(c.OBJECT_ID)='txncustomers'


----------------Get All table that doesn’t have primary key--------------


SELECT name AS Table_Name FROM sys.tables WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasPrimaryKey') = 0 ORDER BY Table_Name;



---------------Get All table that don’t have foreign key------------------


SELECT name AS Table_Name FROM sys.tables WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasForeignKey') = 0 ORDER BY Table_Name;



----------------Get All table that don’t have identity column------------


SELECT name AS Table_Name FROM sys.tables WHERE OBJECTPROPERTY(OBJECT_ID,'TableHasIdentity') = 0 ORDER BY Table_Name;



-----------------Get First Date of Current Month------------------------


SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE()))+1,GETDATE()),105) First_Date_Current_Month;



-----------------Get last date of previous month------------------------

SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE())),GETDATE()),105) Last_Date_Previous_Month;



-----------------Get last date of current month-------------------------

SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE())), DATEADD(MONTH,1,GETDATE())),105) Last_Date_Current_Month;




-----------------Get first date of next month----------------------------
SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE())), DATEADD(MONTH,1,GETDATE())+1),105) First_Date_Next_Month;




-- ---------------Get all tables that contain a view----------------------

SELECT * FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE





-----------------Get all columns of the table that using in views---------

SELECT * FROM INFORMATION_SCHEMA.VIEW_COLUMN_USAGE




 -----------------Get all stored procedure from Database----------------

SELECT DISTINCT o.name, o.xtype FROM syscomments c INNER JOIN sysobjects o ON c.id=o.id WHERE o.xtype='P'



 ---------------- Get all stored procedure from table---------------------

SELECT DISTINCT o.name, o.xtype FROM syscomments c INNER JOIN sysobjects o ON c.id=o.id WHERE c.TEXT LIKE '%txncustomers%' AND o.xtype='P'




 ---------------- View dependencies of stored procedure ----------------

;WITH stored_procedures AS ( SELECT oo.name AS table_name, ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
FROM sysdepends d INNER JOIN sysobjects o ON o.id=d.id INNER JOIN sysobjects oo ON oo.id=d.depid WHERE o.xtype = 'P' AND o.name LIKE '%BeneficiaryEnrolmentDataStatusSave%' ) SELECT Table_name FROM stored_procedures WHERE row = 1 



Difference between N-tier vs N-layer architecture


N-tier and n-layer are entirely different concepts. N-tier refers to the actual and system components of your application. For example: Suppose you create a web application, its components include your application server where it is being hosted, the database being used with it, on another server and the user machine who access the application so These are referred to as the 3 tiers of your application. They may be n in number and so the term n-tier application. So tiers are the physically separate components of the same system.

 On the other hand, layers refer to the internal architecture of your component. For example: in your application code, you divide the code into different layers like the Data access layer (DAL), Business logic layer (BAL), etc. So they are internal to the component and these layers interact with each other internally to form the entire component.


Reflection in C#

Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime. it allows code to inspect other code within the same system. The main class for reflection is the System. Type class, which is an abstract class representing a type in the Common Type System (CTS). When you use this class, you can find the types used in a module and namespace and also determine if a given type is a reference or value type.


Benefits of Reflection C#


1.      Use Module to get all global and non-global methods defined in the module.
2.      Use Assembly to load modules listed in the assembly manifest.
3.      Use PropertyInfo to get the declaring type, reflected type, data type, name and writable status of a property or to get and set property values.
4.      Use MethodInfo to look at information such as parameters, name, return type, access modifiers, and implementation details.
5.      Use EventInfo to find out the event-handler data type, the name, declaring type and custom attributes.
6.      Use ConstructorInfo to get data on the parameters, access modifiers, and implementation details of a constructor.




Constructors in C#


The constructor is special methods which get called automatically when an object of a class is created. Constructors are specially used to initialize data members.

Types of constructors:-
1.     Default Constructor
2.     Parameterized Constructor
3.     Copy Constructor
4.     Static Constructor


   public class SampleClassNitin

    {

        public SampleClassNitin()

        {

            Console.WriteLine("SampleClassNitin  Test Method");

        }
    }

Default Constructor
A constructor without having any parameters called the default constructor.

Parameterized Constructors
A constructor with at least one parameter is called as parameterized constructor.

Constructor Overloading
When we create another constructor with the same method name with different parameters called Constructor Overloading.

Copy Constructor
A parameterized constructor that contains a parameter of the same class type is called as copy constructor.


Static Constructor

If we declared constructor as static and it will be invoked only once that type of constructor is called Static Constructor.


Try-Catch-Finally in c#

Exceptions allow an application to transfer control from one part of the code to another. When an exception is thrown, the current flow of the code is interrupted and handed back to a parent try-catch block. C# exception handling is done with the following keywords: try, catch, finally, and throw

Syntax



try
        {
            //statements that may raise exceptions
        }
        catch
        {
            //Catch the exception
        }
        finally
        {
            //This block of code will always get executed whether an exception occurs or not as long                as there are no exceptions within this block itself.
        }




Example 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class ExceptionHandlingExampleProgram
    {
        static void Main(string[] args)
        {
            object o2 = null;
            try
            {
                int i2 = (int)o2;   // Error 
            }
            catch (Exception exceptionObj)
            {
                // log exception from exceptionObj
            }
            finally
            {

                // do cleanup work here
            }

        }
    }
}