Skip to content

Instantly share code, notes, and snippets.

@StevePy
Created September 23, 2011 15:08
Show Gist options
  • Save StevePy/1237602 to your computer and use it in GitHub Desktop.
Save StevePy/1237602 to your computer and use it in GitHub Desktop.
Property Name Extension Method
using System;
using System.Linq.Expressions;
public static class PropertyNameExtensions
{
/// <summary>
/// Extension method for exposing the name of properties without resorting to
/// magic strings.
/// Use: objectReference.PropertyName( x => x.{property} ) to retrieve the name.
/// I.e. objectReference.PropertyName( x => x.IsActive ); //will return "IsActive".
/// </summary>
/// <returns>
/// Property name of the property expression provided.
/// </returns>
public static string PropertyName<T, TReturn>(this T obj, Expression<Func<T, TReturn>> property) where T : class
{
MemberExpression body = (MemberExpression)property.Body;
if (body == null)
throw new ArgumentException("The provided expression did not point to a property.");
return body.Member.Name;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spynical.Test.NUnit;
using NUnit.Framework;
using System.Linq.Expressions;
namespace PySty.Common
{
public class PropertyNameUnitTests : BaseTestFixture
{
[Test]
public void EnsurePropertyNameCanExtractPropertiesFromObjectInstance()
{
var testObject = new SomeTestObject();
Assert.AreEqual("SomeValue", testObject.PropertyName(x=>x.SomeValue));
Assert.AreEqual("SomeOtherValue", testObject.PropertyName(x=>x.SomeOtherValue));
Assert.AreEqual("SomeKey", testObject.PropertyName(x => x.SomeKey));
}
[CoverageExclude(CoverageExcludeAttribute.TestStubClass)]
private class SomeTestObject : SomeBaseObject
{
public string SomeValue
{
get;
set;
}
public int SomeOtherValue
{
get;
set;
}
}
[CoverageExclude(CoverageExcludeAttribute.TestStubClass)]
private class SomeBaseObject
{
public int SomeKey
{
get;
set;
}
public string SomeMethod()
{
return string.Empty;
}
}
}
}
@MNF
Copy link

MNF commented Mar 20, 2013

I've Added Converted to MS Test PropertyNameUnitTests in https://gist.github.com/MNF/5208179

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment