Monday, December 10, 2007

C# 3.0 Extension Methods

Microsoft introduced the cool and nice features of Extension Methods in C# 3.0.
You can add the methods to the any type like string, int, Collection or even customer class.

you have define and implement the extended methods in static class only and method also static.

Extension Class and Methods:


static class MyExtensionMethods
{

// this methods apply to all string type
public static bool IsNumber(this string input)
{
return !(Regex.IsMatch(input, "[^0-9]"));
}

// this methods apply to all type that derive from object type
public static bool IsExistsIn(this object obj, IEnumerable list)
{
foreach (object o in list)
{
if (o.Equals(obj))
return true;
}

return false;
}
}



Using Extension Methods:

string number = "45";
bool isNum = false;

// returns true
isNum = number.IsNumber();

// returns false
isNum = "45fg".IsNumber();


bool isExists = false;
string[] arr = { "Ayyanar", "Senthil", "Vaithy" };

// returns true
isExists = "Ayyanar".IsExistsIn(arr);

// returns false
isExists = "Ayya".IsExistsIn(arr);



Now we will see how to use this extension methods to custom class object.

Class:


class Customer
{

#region Automatic Properties

public long CustomerID
{
get;
set;
}

public string Name
{
get;
set;
}

#endregion

#region Override Methods

public override bool Equals(object obj)
{
Customer c = (Customer)obj;

if (c.CustomerID == this.CustomerID && c.Name == this.Name)
return true;
else
return false;
}

public override int GetHashCode()
{
return base.GetHashCode();
}

#endregion
}



Using Extension Method for Customer Object:


// C# 3.0 Collection Initializers


List<Customer> custList = new List<Customer>{
new Customer { CustomerID = 1, Name = "Ayyanar" },
new Customer { CustomerID = 2, Name = "Senthil" },
new Customer { CustomerID = 3, Name = "Vaithy" }
};

// C# 3.0 Object Initializers
Customer c = new Customer { CustomerID = 1, Name = "Ayyanar" };

// return true
isExists = c.IsExistsIn(custList);

No comments: