C# Extension Method By Simple Example!

For Example, You want to add new methods to System.Web.UI.WebControls.CheckBoxList
Step One. Declare a static class with *any* name.
Step Two. Declare a static method just like any normal method. This method can have return value and arguments.
Remember, we need to have the first argument define like this *this ClassName object*. In our case :
public static void MethodName(this CheckBoxList checkBoxList)
{
...
}

Okay now, Let’s see an example. Let’s say we want to have all selected checkbox values.
We can do like this.
public static class CheckBoxListExtension
{
public static string[] GetSelectedValues(this CheckBoxList checkBoxList)
{
List l_selected = new List(5);
foreach (ListItem item in checkBoxList.Items)
{
if (item.Selected)
{
l_selected.Add(item.Value);
}
}return l_selected.ToArray();
}
}

Then, when you use it, .NET may tells you that it can’t find that method.
The auto add using won’t work in this situation.
That make sense since the extension methods is not in that extended class.
Just add using YourNameSpace manually and we are good.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s