"nameof" expression is introduced in Visual Studio 2015 and c# 6
nameof (C# and Visual Basic Reference)
How can u use it or write a similar method in older versions like .net framework 4.
"nameof" expression is introduced in Visual Studio 2015 and c# 6
nameof (C# and Visual Basic Reference)
How can u use it or write a similar method in older versions like .net framework 4.
nameOf
- Gets resolved atCompiletime
- if you decompile, you will see that the compiler just translated the classname (without the Namespace(!)) into a constant string instead. So be aware!If you want to get a classe's name use
typeof()
orGetType()
to get the specific (maybe derived) type atRuntime
and read the value ofthe
.Name
-Property in .net < C#6.Read more at MSDN
The nameof operator returns a string representation of the variable you have passed it so nameof(var1) will return "var1", its useful in avoiding code where we have to specificy variable names as strings like in argument exceptions.
In previous versions you could achieve a similar effect using reflection, or expression trees.
To my knowledge there are three options to not have to use a magic string
nameof which requires Visual Studio 2015 (But can be compiled to other versions of the .net framework)
use a method that takes an expression and returns the property name as found in this post "Get string name of property using reflection"
CallerMemberNameAttribute - (Only available in .net framework 4.5, included because original post said older versions like .net framework 4.0 which I guess includes 4.5) The draw back of this method is it is only useful when you need to string representation of the current method you are operating in.
If you're talking about an equivalent for C# before C#6, this will get the job done (in a hacky way) for properties. It can probably be expanded upon to include fields, methods, etc.
Just whipped this up quickly, so there's a lot to be improved, but you use it like this:
Result contains 'myProp'
Update:
More comprehensive (though still not that pretty)
Accessing static properties/fields:
Accessing parameters within functions: