Extension methods enable you to "add" methods to existing types without creating a new derived type or modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. There is no apparent difference between calling an extension method and actually defined methods of that type.
for example lets create an extension method for string type to check whether that particular string can be convert to int or not:
using System;
using System.ComponentModel;
using System.Reflection;
public static class Extension
{
public static bool IsInt(this string str)
{
int iCount = 0;
return int.TryParse(str, out iCount);
}
}
using System.ComponentModel;
using System.Reflection;
public static class Extension
{
public static bool IsInt(this string str)
{
int iCount = 0;
return int.TryParse(str, out iCount);
}
}
And now we can use this static method to check whether a string can be converted to int or not:
string str1="a";
string str2="1";
if(str1.IsInt())
{
Response.Write("string can be converted to int");
}
else
{
Response.Write("string can not convert to int");
}
Few more Examples:
namespace ExtensionMethods
{
public static class Extensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
public static int ActualLength(this string[] strArray)
{
int iCount = 0;
for (int i = 0; i < strArray.Length; i++)
{
if (strArray[i] != string.Empty && strArray[i] != null)
iCount++;
}
return iCount;
}
public static bool IsInt(this string str)
{
int iCount = 0;
return int.TryParse(str, out iCount);
}
public static bool IsLong(this string str)
{
long iCount = 0;
return long.TryParse(str, out iCount);
}
public static string GetEnumDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}
}
}
No comments:
Post a Comment