Skip to content

Instantly share code, notes, and snippets.

@darrencauthon
Forked from srakowski/AModel.cs
Last active June 3, 2016 04:56
Show Gist options
  • Save darrencauthon/6154558ad5c9f9df7c669fb9abee658f to your computer and use it in GitHub Desktop.
Save darrencauthon/6154558ad5c9f9df7c669fb9abee658f to your computer and use it in GitHub Desktop.
Example of Dynamic Proxy ViewModel in C#?
using System;
namespace VMSandbox
{
class AModel
{
public DateTime Date { get; set; } = DateTime.UtcNow;
public int MyLifeForTheCodeDownloads { get; set; } = Int32.MaxValue;
}
}
using System;
namespace VMSandbox
{
class Program
{
static void Main(string[] args)
{
var model = new AModel { Date = DateTime.Now, MyLifeForTheCodeDownloads = 7 };
dynamic plain = new ViewModelBase(model);
Console.WriteLine(plain.Date); // 6/2/2016 11:52:05 PM
Console.WriteLine(plain.MyLifeForTheCodeDownloads); // 7
dynamic special = new SpecialViewModel(model);
Console.WriteLine(special.Date); // 6/2/2016
Console.WriteLine(special.MyLifeForTheCodeDownloads); // 7
}
}
}
namespace VMSandbox
{
class SpecialViewModel : ViewModelBase
{
public SpecialViewModel(object subject) : base(subject) {}
public string Date
{
get { return TheSubject.Date.ToShortDateString(); }
}
}
}
using System.Dynamic;
namespace VMSandbox
{
public class ViewModelBase : DynamicObject
{
public dynamic TheSubject { get; }
public ViewModelBase(dynamic subject)
{
TheSubject = subject;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
var property = TheSubject.GetType().GetProperty(binder.Name);
if (property == null)
return false;
result = property.GetValue(TheSubject).ToString();
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment