Applying Extension Methods to an Interface - C#

Shervan360 1,661 Reputation points
2023-10-02T02:37:14.84+00:00

Hello,

Could you please write an example for applying extension methods to an interface in C#? Which allows me to call the extension method on all the classes that implement the interface.

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-10-02T04:38:45.55+00:00

    Hi @Shervan360 , Welcome to Microsoft Q&A,

    Extension methods are a technique for adding new methods to existing types through static classes. However, the interface itself cannot directly contain extension methods. However, you can create an extension method that accepts an interface as its first parameter and uses the interface's methods in its method body.

    using System;
    
    namespace _10_2_x
    {
        public interface IRunable
        {
            void Run();
        }
        public class Man : IRunable
        {
            public void Run()
            {
                Console.WriteLine("The man is running.");
            }
    
            // Other member methods and properties of the man class
        }
        public static class ManableExtensions
        {
            public static void RunFast(this IRunable Runable)
            {
                Console.WriteLine("Runing faster!");
                Runable.Run(); // Use interface methods
            }
        }
    
        internal class Program
        {
            static void Main()
            {
                Man man = new Man();
                man.Run();      // Call the Run method of the Man class
                man.RunFast();  // Call extension method RunFast
    
                // If there are other classes that implement the IRunable interface, you can also call the RunFast method
                // For example: IRunable otherRunable = new OtherRunable();
                // otherRunable.RunHigh();
    
                Console.ReadLine();
            }
        }
    }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.