Is it possible to add to/change the functionality of a method through a partial class?

91 views Asked by At

I have been working on a nuget-package that helps with sending information to Azure's READ-API. The package itself is done and works great, however I want to add some more optional functionality.In this specific case, I want to send emails when certain milestones are met.

I have made a new project, added my original nuget-package as a reference and went to work with partial classes. While I did succeed in adding some variables and functions, it seems like I cannot change the functionality of the original sendfile method.

I was wondering whether or not it's possible through some other way to either add a function that always executes after the sendfile function, or to change the functionality of it through an extension package?

My searches on the internet have lead me to the Decorator pattern, however this requires you to wrap the original class in another class, which is something I would like to avoid, because I want to make multiple extension packages.

2

There are 2 answers

0
Magnus On

If you inherit from the class you can override sendfile (if it is marked as virtual)

public class BaseClass
{
    public virtual void SendFile() { }
}

public class MyClass : BaseClass
{
    public override void SendFile()
    {
        base.SendFile();
        SendFileCompleted();
    }

    private void SendFileCompleted()
    {
    }
}
0
Guru Stron On

Partial classes were created to split definition of a class, a struct, an interface or a method over two or more source files, hence the following restriction:

  • All partial-type definitions meant to be parts of the same type must be defined in the same assembly and the same module (.exe or .dll file). Partial definitions cannot span multiple modules.

If you have the control over the base nuget (it seems so) you can either use inheritance:

public class Sender
{
    public virtual void SendFile() 
    {
        // do something 
    }
}

public class ImprovedSender : Sender
{
    public override void SendFile()
    {
        // do something new 
        // optionally  base.SendFile();
    }
}

Another useful approaches/patterns in such cases:

public class Sender
{
    public void SendFile() 
    {
        BeforeSendFile();
        // do something or optionally extract virtual SendFileInternal
        AfterSendFile();
    }
    protected virtual void BeforeSendFile() 
    {
    }
    protected virtual void AfterSendFile() 
    {
    }
}
  • Dependency injection - abstract the Sender or some of it's parts as interfaces and use DI so the consumer can completely replace the dependency with custom one.