DEV Community

Jon Stødle
Jon Stødle

Posted on • Originally published at blog.jonstodle.com on

PSA: delegate is a Thing

This is just a short reminder to all C# developers defining and implementing interfaces with a single method:

What you are looking for is delegate

A delegate is a way to define the signature of a method. It can then be implemented by a Func, an Action or class method, whichever fits the best.

They even work nicely with dependency injection: a delegate is just a definition, not an implementation. If you want to preserve testability, that's taken care of: in tests you can just pass in a dummy implementation by way of a Func or Action; no mocking framework needed.

Here's an example

// Definition
public delegate void SendEmail(string recipient, string sender, string subject, string message);

// Registering with a DI system
services.AddTransient(_ => (recipient, sender, subject, message) => { /* Implementation */ });
// or
services.AddTransient(_ => StaticClassWithImplementation.StaticMethodImplementingDelegate);

// In testing
var systemUnderTest = new ClassThatNeedsToSendEmails((_, __, ___, ____) => { log.Info("Sent email"); });
Enter fullscreen mode Exit fullscreen mode

Don't overcomplicate with interfaces and classes, what could simply be a delegate.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more