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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay