Search code examples
c#.net-corepartial-classes

Can you extend a non partial method in a partial class?


I have a generated partial class

public partial interface IPartialInterface
{
   Task<object> Method(string param)
}
public partial class PartialClass : IPartialInterface
{
    public Task<object> Method(string param)
    {
        // does stuff
    }
}

I want to extend the Method so I can plug some logic and then depending on my logic let the PartialClass.Method logic take over or stop it.


Solution

  • For people with the same problem, this worked for me:

        public partial interface IGeneratedPartialInterface
        {
            Task<object> Method(string param)
        }
        public partial class GeneratedPartialClass : IGeneratedPartialInterface
        {
            public Task<object> Method(string param)
            {
                 // does stuff
            }
        }
            
        public interface MyInterface
        {
            Task<object> MethodExtended(string param)
        }
            
        // added by me, but must be named as the generated partial class
        public partial class GeneratedPartialClass : MyInterface
        {        
            public Task<object> MethodExtended(string param)
            {
                // my logic here example
                if (isInCache(param))
                {
                    // do stuff
                }
                else 
                {
                    return this.Method(param)
                }
            }
        }