Here is my situation. I have implemented the accepted .NET 4.0 answer in this question, which is working.
However, my codebase is quite large and as responsible for this code I've started getting inquiries regarding this solution. I've been asked if there are no easier ways of accomplishing the same thing, and if there is any way to shorten the usage.
In almost all cases, this class is used to get or set a single property only. This favors other solutions, since the usage ends up like this: new UserSessionData().CustomerNumber = 123;
The closest thing I have is a class (static or not) with static members and methods, like this:
public static class UserSessionData
{
public static Dictionary<string, string> AsDictionary()
{
return typeof(UserSessionData).GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(null, null) as string);
}
private static string Get(Expression<Func<string>> e)
{
var me = e.Body as MemberExpression;
return ExternalInterfaceClass.Get(me.Member.Name);
}
private static void Set(Expression<Func<string>> e, string value)
{
var me = e.Body as MemberExpression;
ExternalInterfaceClass.Set(me.Member.Name, value);
}
public static string CustomerNumber {
get { return Get(() => CustomerNumber); }
set { Set(() => CustomerNumber, value); }
}
// ... and hundreds more properties similar to "CustomerNumber"
}
This feels like a quite good solution:
- It's strongly typed (i.e. I can easily refactor
CustomerNumber
throughout) - Usage is great (
UserSessionData.CustomerNumber = 123;
) - The boilerplate is not that ugly - I think it's acceptable
However, there is one issue that I can't wrap my head around. Sometimes we need to be able to use this a little differently, A) as a return type and B) bulk-editing the structure before saving. As for A, I understand that a static class cannot be used as a return type, however I don't know what my alternatives would be in this specific situation?
As for B, I guess that I could delay the actual saving by providing a stated subclass and requiring explicit save, but the usage would be worsened for the normal use case (setting or getting a single property) since every one-liner would have to be followed by a call to the save method.
I thought about creating an interface for the class but interfaces can't define static properties. I'm feeling a little muddled here, help is appreciated. Please provide a minimal code example when presenting your thoughts, if possible - it clarifies the point a lot.