Posted by: R Manimaran | December 7, 2010

Using Extensions Methods in SharePoint

In the Previous post we have seen about Extensions and how to use it in C#.

Here we have Some Examples using Extensions Method in SharePoint.

using (SPSite oSPSite = new SPSite(http://server”))


using (SPWeb oSPWeb = oSPSite.OpenWeb())


//Calling a Extensions Method to Check the List Exists

if (!oSPWeb.IsListExists(“Tasks“))


Guid taskListGuid= oSPWeb.Lists.Add(“Tasks“, “Task List“,



//Another extension method Here

SPList taskList = oSPWeb.Lists.GetListByListName(“Tasks“);

//One More Extensions Method on SPList


//Extension Method on SPListItem

SPUser CreatedBy = taskList.Items[0].CreatedBy(oSPWeb);

string email = CreatedBy.Email;

//Extension Method on SPViewCollections

SPView view = taskList.Views.GetViewByName(“AllItems“);



Our Extensions Methods

IsListExists à Extension on SPWeb

public static bool IsListExists(this SPWeb web, string name)


bool exists = false;



SPList list = web.Lists[name];

exists = true;




exists = false;


return exists;


GetListByListName à Extension on SPListCollection

public static SPList GetListByListName(this SPListCollection lists, string name)


if (lists != null && !string.IsNullOrEmpty(name))


foreach (SPList list in lists)


if (string.Compare(list.Title, name,StringComparison.OrdinalIgnoreCase) == 0)


return list;




return null;


ClearItems à Extension Method on SPList

public static void ClearItems(this SPList list)


int ItemCount = list.ItemCount;

SPListItemCollection itemCollections = list.Items;

foreach (SPListItem item in itemCollections)





CreatedBy à Extension Method on SPListItem

public static SPUser CreatedBy(this SPListItem item,SPWeb oWeb)


string userName =item[“Author”].ToString();

SPFieldUserValue loginUserValue = new SPFieldUserValue(oWeb, userName);

return loginUserValue.User;



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


%d bloggers like this: