Feeds:
Posts
Comments

Posts Tagged ‘static class’

What are extension methods?

What are extension methods?

This method allows us to add a new static method to the existing classes.

Example

class Program
    {
        static void Main(string[] args)
        {
            int x = 3;
            Console.WriteLine(x.factorial());
            Console.ReadLine();
        }
    }
    public static class MyMathExtension
    {
        public static int factorial(this int x)
        {
            if (x <= 1) return 1;
            if (x == 2) return 2;
            else
                return x * factorial(x – 1);
        }
    }
Use Of This

  1.     Extension methods allow existing classes to be extended without relying on inheritance or having to change the class’s source code.
  2.     If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced i.e. extension methods.
  3.     This feature is important for all developers especially if you would like to use the dynamism of the C# enhancements to be taken place in your classes design.

Important points while using extension methods:

  1.     An extension method must be defined in a top-level static class.
  2.     An extension method with the same name and signature as an instance method will not be called.
  3.     Extension methods cannot be used to override existing methods.
  4.     The concept of extension methods cannot be applied to fields, properties or events.
  5.     Overuse of extension methods is not good style of programming.

Read Full Post »