Extension is static method, beware of its namespace

If you are using extension method within same namespace, carefully choose your method names.
Because extension methods is actually treat as static methods.
So, if you have extension method isEmpty() for let’s say Guid and TextBox.
And both of them are in namespace Your.Extension. The compile will complete without a problem.
But you will encounter error at runtime since both static methods have the same name.
You can either choose another name or separate them in different namespace.

Advertisements

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.