SharePoint provides a Feature Receiver class that can be used to respond to Feature Events. This class allows us to trap a particular Feature Event and execute custom C# code within that. The Feature Receiver class can be associated with the Feature by setting the ReceiverAssembly and ReceiverClass attribute within the Feature element tag.

So if you want to perform any action programmatically using C# code  when feature is installed, uninstalled, activated or deactivated, then you just need to create a feature receiver class and override the feature events and write your custom code there. To create a feature receiver class, create a normal C# class and inherit is from SPFeatureReceiver class which can be found under Microsoft.SharePoint namespace. Following are the various Feature Events which we can override in the custom feature receiver class:

Feature Event Description
FeatureActivated An event that occurs when a feature is activated
FeatureDeactivating An event that occurs when a feature is deactivated
FeatureInstalled An event that occurs when a feature is installed
FeatureUninstalling An event that occurs when a feature is uninstalled

You can have a look on a sample feature receiver class below:

using System;

using Microsoft.SharePoint;

 

public class FeatureReceiverClass1: SPFeatureReceiver

{

    public override void FeatureActivated(SPFeatureReceiverProperties properties)

    {

        // Write your custom C# code here

    }

 

    public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

    {

        // Write your custom C# code here

    }

 

    public override void FeatureInstalled(SPFeatureReceiverProperties properties)

    {

        // Write your custom C# code here

    }

 

    public override void FeatureUninstalling(SPFeatureReceiverProperties properties)

    {

        // Write your custom C# code here

    }

}

Once you have created the feature receiver class, deploy its assembly into GAC and add the reference of feature receiver class into the respective SharePoint Feature. A sample Feature element tag is given below:

<Feature Id="GUID" Title="Feature Title" 
    Description="Feature Description" 
    Version="1.0.0.0" 
  Scope="Site"
  Hidden
="false"
ReceiverAssembly="FeatureReceiverAssembly1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ag37htreswd6g45j"
ReceiverClass="FeatureReceiverAssembly1.FeatureReceiverClass1">
</Feature>