Search code examples
c#.net-coreextension-methods

how to overload an extension method that is doing the same thing but different arguments


Im trying to prevent duplicating an extension code For instance UrlHelper(this SomeDataEventClass e) and UrlHelper(this AnotherDataEventClass e). They are doing the same thing which is generating urls based on the class .

However is there another way to further simplify the two methods to prevent method duplication


Solution

  • You could make a extension method on a base class or interface that both of your classes extend/implement. This can then only use fields from the base class or interface. Or you'd need to check which type you are currently handling but that breaks the abstractions you are adding and would vouch for multiple implementations.

    With Base class:

    public abstract class BaseClass
    {
        public string DomainName { get; set; }
    }
    
    public class ClassA : BaseClass
    {
    
    }
    
    public class ClassB : BaseClass
    {
    
    }
    
    public static class DataExtensions
    {
        public static string UrlHelper(this BaseClass baseClass)
        {
            return baseClass.DomainName + ".com";
        }
    }
    
    public class SomeLogic
    {
        public void DoStuff()
        {
            var a = new ClassA();
    
            var url = a.UrlHelper();
    
            var b = new ClassB();
    
            var urlb =  b.UrlHelper();
        }
    }
    

    With interface:

    public  interface BaseInterface
    {
        public string DomainName { get; set; }
    }
    
    public class ClassA : BaseInterface
    {
        public string DomainName { get; set; }
    }
    
    public class ClassB : BaseInterface
    {
        public string DomainName { get; set; }
    }
    
    public static class DataExtensions
    {
        public static string UrlHelper(this BaseInterface baseInterface)
        {
            return baseInterface.DomainName + ".com";
        }
    }
    
    public class SomeLogic
    {
        public void DoStuff()
        {
            var a = new ClassA();
    
            var url = a.UrlHelper();
    
            var b = new ClassB();
    
            var urlb =  b.UrlHelper();
        }
    }