Archive for June, 2012

Determining a property name using a lambda expression

June 21, 2012
public static string PropertyNameFor<T>( Expression<Func<T>> propertyExpression ) {
  return ( propertyExpression.Body as MemberExpression ).Member.Name;
}
Usage:
string name = PropertyNameFor( () => this.NumberOfLanguagesDisplayed );
Assert.IsTrue( "NumberOfLanguagesDisplayed", name );

Generic tryParse of a string

June 20, 2012

A useful generic approach to parsing a string to any type.

bool tryParse<T>( string input, out T result ) {
  result = default( T );
  var converter = TypeDescriptor.GetConverter( typeof( T ) );
  if( converter != null ) {
    object resultAsObject = converter.ConvertFromString( input );
    if( resultAsObject == null ) return false;
    result = (T)resultAsObject;
    return true;
 }
 return false;
}