It’s been few days since I wrote anything as I was enjoying my christmas vecation 🙂 Hope you all had a wonderful holiday time celebrating christmas.
What I am going to share today is about using extension methods in .Net.I faced this scenario recently & thought will make a note of this so that months later I can look back & remember what I learnt. Extension methods are a special kind of static method that enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
For example if you are using LINQ to read a OracleDataReader & want to check if a column exists in a DataReader object,we do not have a direct method that does so.Here comes the use of a custom extension method.These are the steps to follow
namespace Helper
{
public static class Extension
{
public static bool HasColumn(this IDataRecord dr, string columnName)
{
for (int i = 0; i < dr.FieldCount; i++)
{
if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
return true;
}
return false;
}
}
}
Note that the first parameter is not specified by calling code because it represents the type on which the operator is being applied, and the compiler already knows the type of your object. You only have to provide arguments for parameters 2 through n.
public void Format(OracleDataReader reader)
{
try
{
bool iscolumnexist = reader.HasColumn(“Description”);
}
catch (Exception ex)
{
throw;
}
}
Hope you find this code snippet useful 🙂