Saturday, February 13, 2010

Extension Methods - add methods to class

Consider the following class
  public class Person
        public string FirstName { get; set; }
        private string LastName { get; set; }
        protected string Email { get; set; }
        public int Age { get; set; }
       virtual public void showName()
            Console.WriteLine("base class");

To add additional methods to a class you have to subclass it or add the function directly to the class. If the class is sealed then you will have very limited options only.

In C#, you can use the new extension method feature to add a new method to an existing type. To add the method to the existing class, define a new static class and define the
extension method (a static method) within it like the following

    static class ExtensionMethods
        public static string AddMarks(this Person per,double marks1, double marks2)
            return (marks1 + marks2).ToString();

The first parameter of an extension method is prefixed by the this keyword, followed by the type it is extending (Person in this example, indicating to the compiler that this extension method must be added to the Person class). The rest of the parameter list (if any) is then the signature of the extension method.

(In the figure you can see the new extension method for the Person object )
If an extension method has the same signature as another method in the class it is trying to extend, the method in the class will take precedence and the extension method will be ignored.
Post a Comment