Light metaprogramming scenarios
Attribute driven helpers: display labels, required validation, mini constructor activator, and CSV like serialization with clear safety tips.
Plan & scope
Aim: Drive tiny behaviors with attributes.
- Map labels
- Validate required fields
- Mini DI activator
- Serialize to CSV like text
Attribute labels
Decorate properties with a DisplayName and reflect it to print friendly labels.
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Property)]
public sealed class DisplayNameAttribute : Attribute
{
public string Text { get; private set; }
public DisplayNameAttribute(string text) { Text = text; }
}
public sealed class User
{
[DisplayName("User Id")]
public int Id { get; set; }
[DisplayName("Full Name")]
public string Name { get; set; }
}
public class Program
{
static void PrintWithLabels(object o)
{
if (o == null) throw new ArgumentNullException("o");
Type t = o.GetType();
foreach (PropertyInfo p in t.GetProperties())
{
object[] at = p.GetCustomAttributes(typeof(DisplayNameAttribute), false);
string label = at.Length > 0 ? ((DisplayNameAttribute)at[0]).Text : p.Name;
object val = p.GetValue(o, null);
Console.WriteLine(label + ": " + (val == null ? "null" : val.ToString()));
}
}
public static void Main(string[] args)
{
User u = new User { Id = 1, Name = "Ada" };
PrintWithLabels(u);
}
}
All lessons in this course
- Type, MethodInfo, activation, custom attributes
- Source-level info (Caller attributes)
- Light metaprogramming scenarios