Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Func<> delegates in library

The generic Func<> and Action<> delegates from later versions of .NET are very appealing, and it's been demonstrated in many places that these can easily be recreated in code targeting .NET 2.0, such as here.

From the perspective of a library targeting .NET 2.0 however, which may be consumed by applications built against any higher version of .NET, how does this stack up. Is implementing this "compatibility layer" within the library absolutely a recipe for conflict (both in terms of private and public interface), or are there ways to make this work independent of the target framework that the consuming application builds against?

If this is a non-starter, would it be better to either: A) Define an identical set of parametrized delegates with different names? or.. B) Stick strictly with .NET 2.0 convention, and define new delegate types as I need them?

like image 876
Justin Aquadro Avatar asked Jun 28 '11 01:06

Justin Aquadro


1 Answers

The plain truth is that Func<> and Action<> are a good idea. They make your code much easier to read and they avoid a shocking amount of messy boilerplate delegate declarations. That's why you want to use them.

So you have this really appealing programming style you want to use, it's a standard technique that is now used almost universally instead of the old way, but you can't use it because you are targeting a legacy version of the framework. What should you do?

You have three choices:

  1. Use the programming style that was in common use before the feature
  2. Add the feature to your own code in spirit but with non-conflicting names
  3. Add the feature to your own code with the "real" names but in your own namespace

Using the old programming style gives up all the benefits that we have come to appreciate from the feature. That's a big sacrifice. But maybe all your co-developers are used to this style of programming.

Using the feature with non-conflicting names seems sensible enough. People will be able to read the code and benefit from the features, but no-one will be confused that they appear to be something that they're not. When you are finally ready to upgrade, you'll have to patch up the names. Luckily Ctrl+R, Ctrl+R makes doing that very easy.

Using the feature with the same names as the standard feature means your code can target an older version but appear to be using newer features. Seems like a win/win. But this could cause confusion and you have to be careful that your types aren't exposed to other unknowing assemblies, possibly causing source level compilation problems. So you have to be careful and be perfectly clear about what is happening. But it can work effectively.

You have to pick whatever approach makes sense in your situation depending on your needs. There is no one right answer for everybody, only trade-offs.

like image 169
Rick Sladkey Avatar answered Sep 20 '22 17:09

Rick Sladkey