A C# (Over-)Engineering Project - CodeTextAdapter
Frequently, I need to deal with tables that map a code to some text. I prime example would a list mapping state abbreviations to the full state name (e.g.
"New Jersey"). Or perhaps some status code to it’s meaning (
In for those, we’d probably write a collection of methods to deal with them, which we’d need a common interface for them, something like this:
Then we’d be able to write a method that we could use on any of them, something like this:
And everyone’s happy — Except if we have a class holding a State name and it’s abbreviation, then we probably don’t want those fields called
Text. We’d probably prefer calling them something like
Abbrev. But if we change the property names, then it no longer matches the interface, and nothing works.
Which I why I wrote
CodeTextAdapter a helper base class which solves this problem. One uses it like this:
The key parts are the base class, which takes, as it’s generic type parameter, the class that’s being defined (A technique known is some quarters as the Curiously recurring template pattern ). And the constructor, where the
base() constructor call take two lambdas, which respectively, retrieve that Code and Text values.
If you want to create a specialized constructor for your class, just make sure you include a
this() call in it, as shown here. (If you forget, it won’t compile.)
Here’s the code for the adapter itself: