Extension Methods are used to add new methods to a class
without creating a derived class. You define extension methods in a static
class. The methods are also static methods but are called as if they were
defined as a method in the class.
Two uses of these are to isolate common HTML code in ASP websites so you only have to write the code once. Another use of this is to write LINQ query extension methods so you can write queries like:
Two uses of these are to isolate common HTML code in ASP websites so you only have to write the code once. Another use of this is to write LINQ query extension methods so you can write queries like:
Code:
var orders =
_orderRep.GetOrders().ByCustId(5).ByStatus(0);
Example:
Code:
static class ExtensionMethods {
public static bool IsStringEmpty(this
string str) {
return str.Length() == 0;
}
}
You can then call this method as follows:
Code:
var s = new string(“a”);
bool x = s.IsStringEmpty();
Taking a look at the extension method:
Code:
public static bool IsStringEmpty(this string
str) {
The type that the method is called
on has to be prefixed with “this”.
Passing Parameters to Extension Methods
This is simple, you simply add your parameters after you define the type that this method is going to apply to.
Passing Parameters to Extension Methods
This is simple, you simply add your parameters after you define the type that this method is going to apply to.
Code:
public static bool StringStartsWith(this
string str, string s) {
return str.StartsWith(s);
}
You can then call this function like
this:
Code:
string s = "a";
if(a.StringStartsWith(“a”))
Data
Structures Example is Empty
Previously when we looked at queues and stacks we mentioned how we do not have a method to check if the structure is empty. If we wanted this functionality we had to use Count and check if it was 0. If we want a method to accomplish this task we can alternatively write an extension method as follows:
Previously when we looked at queues and stacks we mentioned how we do not have a method to check if the structure is empty. If we wanted this functionality we had to use Count and check if it was 0. If we want a method to accomplish this task we can alternatively write an extension method as follows:
Code:
public static bool IsEmpty(this Queue q) {
return q.Count == 0;
}
Then we can call this method like this:
Code:
Queue<int> q = new Queue<int>();
q.Enqueue(5);
q.Enqueue(3);
if (q.IsEmpty()){
Console.WriteLine("empty");
} else {
Console.WriteLine("not empty");
}
There are two more uses of this we will look at in the future. Extending LINQ queries we will look at when we introduce using LINQ with arrays of objects and when we start looking at ASP.NET websites.
In the meantime, if you have any questions feel free to ask.
No comments:
Post a Comment