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.