[Serializable]
public class SampleBase
{
[HumanReadableAttribute("The Base")]
public string BaseProp { get; set; } // "testing things"
public bool AllUrBase { get; set; } // true
public string AsHumanReadable()
{
var type = GetType();
var properties = type.GetProperties();
var stringRepresentation = new List<string>();
foreach (var p in properties)
{
var ca = p.GetCustomAttributes(true).FirstOrDefault(a => a is HumanReadableAttribute);
var v = p.GetValue(this, null);
var t = v.GetType();
var e = t.IsEnum ? t.GetField(Enum.GetName(t, v)).GetCustomAttributes(typeof(HumanReadableAttribute), false).FirstOrDefault() as HumanReadableAttribute : null;
stringRepresentation.Add(string.Format("{0}: {1}", ca ?? p.Name, v is bool ? ((bool) v ? "Yes" : "No") : e ?? v));
}
return string.Join("\r\n", stringRepresentation);
}
}
[Serializable]
public class SampleClass {
public enum MyEnum {
[HumanReadableAttribute("It makes sense")]
MakesSense,
[HumanReadableAttribute("It's weird")]
Nonsense
}
[HumanReadableAttribute("What do you think about this")]
public MyEnum MyProperty { get; set; } // Nonsense
}
Calling the AsHumanReadable method will produce
The Base: testing things
AllUrBase: Yes
What do you think about this: It's weird
My users may add SampleClass objects (or a wide range of other objects implementing SampleBase) to a shopping cart which will stored for later use.
A customer care worker will be reading the output for checking up on things.
I’ve thought about making ToString methods (like return "The Base" + BaseProp;) instead. My frist thought is that the attribute approach is the more flexible one.
What are the pros and cons to those two approaches (maintainance, localization (avoid magic strings when possible) etc.)?
I recommend dropping the custom implementation and having a look at
ServiceStack.Text, in particular at theT.Dumpmethods.It’s something already implemented and reliable. The only thing that it doesn’t cover are friendly boolean strings (Yes/No)/.
A custom implementation involves first creating a good and working solution, which takes time and then maintenance and adding support for new stuff, which also takes time.
There are many ways through which you can do it, with attributes being one of them, but it’s simply not worth it when you have
ServiceStack.Ultimately, you could modify the T.Dump methods and customize them to fit your requirements. It’s still something not from scratch.