I was looking for an easy and consistent way of creating properties for classes. I sometimes find that it can be a long drawn out process creating 5 to 100 properties for database classes. Here is a quick example of what I did.
You will need the following references to make this example work.
- System.Diagnostics;
- System.Reflection;
- System.Collections;
public class ErrorLogRecord
{
Hashtable _hsh = new Hashtable();
public DateTime DateOfOccurance
{
get { return (DateTime?)_hsh[GetName()] ?? DateTime.Now; }
set { _hsh[GetName()] = value; }
}
public String ErrorText
{
get { return (String)_hsh[GetName()]; }
set { _hsh[GetName()] = value; }
}
public String GetName()
{
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
return methodBase.Name.Replace("set_", "").Replace("get_", "");
}
}
While this method is probably not perfect and could be argued there is a better way, this seems to satisfy the need. I would welcome alternatives.
Alternate Reading: Shortcut To Creating Properties in C-Sharp (revisited)