Get variables and parameter names in C#
In C#, the method of obtaining variables or parameter names depends on the C#version used.
C# 6.0 The solution before
Before C# 6.0, you can use the method in the
class.
MemberInfoGetting
GetMemberName
Get variable name:
<code class="language-csharp">public static string GetMemberName<T>(Expression<Func<T>> memberExpression) => ((MemberExpression)memberExpression.Body).Member.Name;</code>
Get parameter name:
<code class="language-csharp">string testVariable = "value"; string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);</code>
C# 6.0 and higher version solutions
<code class="language-csharp">public class TestClass { public void TestMethod(string param1, string param2) { string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1); } }</code>
C# 6.0 introduced the operator, providing a simple method of acquiring the name:
This method is suitable for variables, parameters and attributes. nameof
The above is the detailed content of How Can I Retrieve Variable and Parameter Names in C#?. For more information, please follow other related articles on the PHP Chinese website!