for example, you had a simple asp.net dropdownlist control and it contains a value for id, and these id's is integers.
so to get the value you need to do something like this
int id = Convert.ToInt32(ddl.SelectedValue);
but what if the SelectedValue was not integer, this will through an .net exception, so you need to write more code, to make sure that the selected value is not empty string. and so on.so here comes the Extension methods.
the class must be static and the method also must be static and you need to decide which object the method will work on. it can be int, string or even object the parent class for every other classes on .net,
so, I'm gonna stick with the dropdownlist example right now.
namespace Demo
{
public static class Extension
{
public static int ToInt(this string val)
{
int d = 0;
if (!string.IsNullOrEmpty(val.Trim()))
int.TryParse(val.Trim(), out d);
return d;
}
}
}
as you can see here the namespace is Demo, the class is static and also the method is static.
now how to use it.
now how to use it.
using Demo; string str = "34"; int convertedNum = str.ToInt();just like this, and the default value will be there, also if there was any error it will be zero.