Background
I have a convenience class, which is essentially a dictionary that contains a list of tag / value pairs to represent in the API.
At the most basic level, all I have done is this:
enum Tag { Name, Date, //There are many more } class RequestDictionary : Dictionary<Tag, string> { }
This complies well with the requirements of the API, as all this is sent and parsed as a string. However, this is not so great for the caller; for example, the caller needs to know how to format Date correctly.
To solve this problem, I started adding tag properties that are type safe. I sequestered them in a separate interface, so they are not confused with the usual properties of the dictionary.
enum Tag { Name, Date } interface ITags { string Name { get; set; } DateTime Date { get; set; } } class RequestDictionary : Dictionary<Tag, string>, ITags { public ITags Tags { get { return this; } } string ITags.Name { get { return this[Tag.Name]; } set { this[Tag.Name] = value; } } DateTime ITags.Date { get { return DateTime.ParseExact(this[Tag.Date], API_DATE_FORMAT, CultureInfo.InvariantCulture); } set { this[Tag.Name] = value.ToString(API_DATE_FORMAT); } } }
After introducing this interface, the caller has a choice
dict[Tag.Date] = DateTime.Now.ToString(API_DATE_FORMAT);
or
dict.Tags.Date = DateTime.Now;
The latter works less for the caller, especially since API_DATE_FORMAT is actually closed.
Problem
I want the caller to be able to use the object initializer syntax:
var dict = new RequestDictionary { Tags.Date = DateTime.Now }
... but this does not compile (error "Invalid initializer element declarator").
So it seems that the caller will need to use
var dict = new RequestDictionary { { Tags.Date, DateTime.Now.ToString(API_DATE_FORMAT) } };
... which is obviously not so well encapsulated or convenient.
Is there a way to initialize an object using the object initializer syntax when the property you want to access is opened through an interface that is not included in the default class interface?