There has been a lot of sentiment to include a nameof
operator in C#. As an example of how this operator would work, nameof(Customer.Name)
would return the string "Name"
.
I have a domain object. And I have to bind it. And I need names of properties as strings then. And I want them to be type-safe.
I remember coming across a workaround in .NET 3.5 which provided the functionality of nameof
and involved lambda expressions. However, I have not been able to locate this workaround. Can anyone provide that workaround to me?
I am also interested in a way to implement the functionality of nameof
in .NET 2.0 if that is possible.
The answer from reshefm is pretty good, but this is a little bit simpler API IMO:
Usage example:
NameOf.Property(() => new Order().Status)
Full code is here: http://agiledesignutilities.codeplex.com/SourceControl/changeset/view/b76cefa4234a#GeneralPurpose/NameOf.cs
This code basically does that:
(Of course it is 3.5 code...)
The workaround is to use an expression tree, and to take that expression tree apart to find the relevant
MemberInfo
. There's slightly more detail and comment in this note (although not the code to pull out the member - that's in another SO question somewhere, I believe).Unfortunately as expression trees don't exist in .NET 2.0, there's really no equivalent.
One solution to avoid typos is to have a set of accessors which fetch the relevant
PropertyInfo
for a particular property, and unit test them. That would be the only place which had the string in it. This would avoid duplication and make refactoring easier, but it's a bit draconian.An extension to what reshefm did, that simplified the usage of the nameof() operator, and gives the names of methods and class members and methods as well:
To use it:
Unless someone changes their mind, the
nameof
operator looks like it's coming in C# 6. Here are the design meeting notes about it:https://roslyn.codeplex.com/discussions/552376
https://roslyn.codeplex.com/discussions/552377
While reshefm and Jon Skeet show the proper way to do this using expressions, it should be worth noting there's a cheaper way to do this for method names:
Wrap a delegate around your method, get the MethodInfo, and you're good to go. Here's an example:
Unfortunately, this works only for methods; it does not work for properties, as you cannot have delegates to property getter or setter methods. (Seems like a silly limitation, IMO.)