Here's an example of auto-setting properties in a pseudo-
decorator pattern in C#, where the decorator is a derived class that automatically sets properties on its base class.
This is somewhere between a decorator and a
wrapper or
facade. For straight forward cases it saves the work of manually setting properties of the base class from the instance passed in on the constructor.
using System;
using System.Linq;
namespace RootSilver
{
public class User
{
public string FirstName{ get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public long Phone1 { get; set; }
public DateTime SignupDate { get; set; }
}
public sealed class DecoratedUser : User
{
public DecoratedUser(User user)
{
user.GetType()
.GetProperties()
.ToList()
.ForEach( x =>
x.SetValue(this,
user.GetType().GetProperty(x.Name)
.GetValue(user, null),
null));
}
public void PrintProperties()
{
this.GetType().GetProperties().ToList().ForEach( x =>
Console.WriteLine(x.GetValue(this, null)));
}
}
public class Test
{
public static void Main()
{
User user = new User
{
FirstName = "Bob",
LastName = "Smith",
Address1 = "11 Main Street",
Address2 = "Apt 2",
City = "Candor",
State = "New York",
Zip = 13743,
Phone1 = 6075551212,
SignupDate = DateTime.Now
};
DecoratedUser decoratedUser = new DecoratedUser(user);
decoratedUser.PrintProperties();
Console.ReadKey();
}
}
}