Created
September 23, 2011 15:08
-
-
Save StevePy/1237602 to your computer and use it in GitHub Desktop.
Property Name Extension Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've Added Converted to MS Test PropertyNameUnitTests in https://gist.github.com/MNF/5208179