I have a database object class that does a bunch of heavy lifting. I then extend that object and build out the classes that represent the actual objects and fields being modified. It basically looks like this:
public class MyObject : DatabaseObject
{
public string FieldX
{
get { return GetValue<string>("FieldX"); }
set { SetValue<string>("FieldX", value); }
}
public int FieldY
{
get { return GetValue<int>("FieldY"); }
set { SetValue<int>("FieldY", value); }
}
}
public class DatabaseObject
{
public T GetValue<T>(string FieldName)
{
// Code that actually gets the right value
}
public void SetValue<T>(string FieldName, T value)
{
// Code that actually sets the value in the right place
}
}
This way, I can later just instantiate MyObject and start setting the properties via code. The idea is to produce easier, more maintainable code.
It works great in practice. However, I'm noticing that the code for MyObject is pretty repetitive. For example, with FieldX, I end up specifying the "string" type inside the get/set, and also having to specify the property name "FieldX" in get/set, as well.
I'm wondering if there's a way to simplify the code further to reduce repetition.
I know I can use Reflection:
MethodBase.GetCurrentMethod().Name.Substring(4)
...inside the get/set calls to get the property name, and I can use GetType() to get the type of value when doing set, but ideally I'd like to get the original property name from within the base GetValue/SetValue methods (ideally without parsing the stack trace).
Ideally, I'm looking for something like this:
public string FieldX
{
get { return GetValue(); }
set { SetValue(value); }
}
public int FieldY
{
get { return GetValue(); }
set { SetValue(value); }
}
Any thoughts?