Bhavya

Code -> Break -> Fix -> Blog

Extension Methods (C#)

Leave a comment

What are Extension Methods?

As the name suggests, extension methods are used to extend the functionality of an existing Type (like Class, Interface etc.) when the developer neither wants to derive the existing Type nor re-compile the existing Type.

The feature was added in C# 3.0.

How to implement Extension Methods?

1. Create a static class.

2. Create a static method (which you want to add to the existing Type).

3. The 1st parameter (mandatory) for the static method should be <<this MyType variable-name>>, followed by other parameters (if required).

4. Check the extension method symbol

snippet

Sample:

 public static class MyExtensionClass
    {
        public static bool IsInteger(this string inputString)
        {
            int ignoredOutput;
            return int.TryParse(inputString, out ignoredOutput);
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            string myString = &quot;100&quot;;

            Console.WriteLine(myString.IsInteger() ? &quot;Integer&quot; : &quot;Not an Integer&quot;);

            Console.ReadKey();
        }
    }

Extension Methods for Interfaces.

 public interface IMyInterface
    {
        void myInterfaceMethod();
    }

    public class MyClass : IMyInterface
    {

        public void myInterfaceMethod()
        {
            Console.WriteLine(&quot;In myInterfaceMethod...&quot;);
        }
    }

    public static class MyExtensionClass
    {
        public static void myExtensionMethod(this IMyInterface my)
        {
            Console.WriteLine(&quot;In myExtensionMethod...&quot;);
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            IMyInterface iMyInterface = new MyClass();
            iMyInterface.myExtensionMethod();

            Console.ReadKey();
        }
    }

Can we add extension methods which has the same signature as that of an existing method?

YES but the extension method will never be called.

Can we add extension methods to Interface, Enums, Abstract classes & static classes?

We can add extension methods for Interface, Enums & Abstract classes but not for static classes.

Possible to override and overload extension methods?

Override – NO

Overload – Yes

~BS
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s