Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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;
}
}
}
}
Owner

StevePy commented Sep 24, 2011

Corrected some formatting issues that were introduced when I had added the code to my blog.

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