Tuesday, May 1, 2018

Extension Methods (C#)


Purpose:

Enable us to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Why:

Sometimes, when using system library, the built-in funciton might not be suitable enough for our needs. Therefore, we need to write some customized function to deal with it. We might creat Util class and put our new function inside it.

For example:
public static class Util {
        public static string ConvertStringForSomePurpose(string s) {
            // todo
            return result;
    }
}

class Program {
    static void Main(string[] args) {
            string s = “test”;
            var newString = Util. ConvertStringForSomePurpose (s);
    }
}


We have another way to satisfy this purpose with Extension Methods.


Extension Methods are a special static method. It need the special key word called ‘this’. In addition, it should be the first parameter.
public static class Util {
        public static string ConvertStringForSomePurpose(this  string s) {
            // todo
            return result;
    }
}

class Program {
        static void Main(string[] args) {
            string s = “test”;
            var newString = s. ConvertStringForSomePurpose();
    }
}


Furthermore, it is widely used when doing lots of LINQ query.


For example, assume we already have some query to get all the students who are male.
// First Query
Var students = from s in students
                           select s.Gender = ‘Male’;
                                   

Unfortunately, clients want to get not only the Male students, but also, they want all selected male students are over 18 ages.  But we do not want to modify this query, because this query has been used by another function already. In order not to modify the first Query, we can use extension methods to handle it.

Public static IQueryable <Student> Valid(this IQueryable <Student> query) {
        Var adultMaleStudents = from q in query
                                           Where q.Age > 18
                                           Select q;
        return adultMaleStudents;
}

// After first Query
var validStudents = students.Valid();

Therefore, we do not need to modify the original query at all.