Another delegate which I think is worth writing a post about is the Converter delegate. This delegate takes the following signature:
Converter<TInput, TOutput>
The idea being, conversion of one type to another. A quick and easy example of this might be if you want to convert a System.String object to a “Registry Hive” object (a root RegistryKey object). The following code demonstrates that:
public static RegistryKey GetRegistryKeyFromString(string name)
{
return typeof(Registry).GetMembers().OfType<FieldInfo>()
.Where(f => f.Name.Equals(name, StringComparison.Ordinal))
.Select(f => f.GetValue(name) as RegistryKey).FirstOrDefault();
}
And usage:
private static Converter<string, RegistryKey> stringToHiveConverter;
static void Main(string[] args)
{
stringToHiveConverter = Converters.GetRegistryKeyFromString;
var registryHive = stringToHiveConverter("CurrentUser");
}
While I am talking about the registry, I will take this opportunity to set out a class which I use to abstract away the Registry and operations on it. At the moment, it is not very sophisticated and only really deals with strings. However, if I ever need to evolve it beyond that, this class is a good starting point. And apropos of converters, it contains a converter which converts strings to RegistryView objects. The constructor permits the user of the class to pass it a custom converter, giving the user more control over how that conversion takes place:
Hopefully that class serves you as well as it served me!