Friday, 21 October 2011

Static Reflection

Here is my example on static reflection(i have used INotifyPropertyChanged, but a simple code as i don't pass around the interface)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.ComponentModel;

namespace StaticReflection
{
public class Customer : INotifyPropertyChanged
{
private string employer = String.Empty;
private string mobile = String.Empty;

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}

public string Employer
{
get { return this.employer; }
set
{
if (value != this.employer)
{
this.employer = value;
NotifyPropertyChanged(this.PropertyName(c => c.Employer));
}
}
}

public string Mobile
{
get { return this.mobile; }

set
{
if (value != this.mobile)
{
this.mobile = value;
NotifyPropertyChanged(this.PropertyName(c => c.Mobile));
}
}
}
}

public static class CustomerExtensions
{
public static string PropertyName(this Customer target, Expression<Func<Customer, object>> expression)
{
return new PropertySpecifier<Customer>(expression).PropertyName;
}
}

public class PropertySpecifier<T>
{
//http://joelabrahamsson.com/entry/getting-property-and-method-names-using-static-reflection-in-c-sharp - Use this article to build a accomplished! PropertySpecifier function
public PropertySpecifier(Expression<Func<T, object>> expression)
{
if (expression == null) return;

if (expression.Body is MemberExpression)
{
this.PropertyName = (expression.Body as MemberExpression).Member.Name;
}
}

public string PropertyName
{
get;
set;
}
}
}