0

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.

  • Have you heard of [partial methods](https://stackoverflow.com/questions/36558244/partial-methods-in-c-sharp-explanation)? That's the best you'll be able to get. – gunr2171 Nov 12 '21 at 13:05
  • short answer. you can't. you can't even "extend" a partial method; that's just a declaration meaning "implemented elsewhere". and think about it: in _what order_ would the two parts be executed? what would variable scopes be like? – Franz Gleichmann Nov 12 '21 at 13:05
  • Thanks, @FranzGleichmann. I searched for a bit and couldn't find anything. Thought it was just me, but guess not ;( – Emil Aleksandrov Nov 12 '21 at 13:07
  • [The Manual](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/partial-method) is quite informative on what partial methods can and can't do. but in short it's limited to: one part (the generated) of the class defines what the method signature looks like, one part (the user-written) optionally defines what it does. and in the end, you're simply limited to what the generator generated. – Franz Gleichmann Nov 12 '21 at 13:11
  • For me, it sounds like inheritance is the way to go here. – PMF Nov 12 '21 at 13:39

1 Answers1

0

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)
            }
        }
    }
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 12 '21 at 15:23