Home >Backend Development >C++ >How Can I Retrieve Variable or Parameter Names in C#?
Get the variable or parameter name in C#
In C#development, you may need to obtain the name of the variable or parameter for various purposes. The way to achieve this goal depends on your C#version.
C# 6.0 Edition: Use the custom auxiliary class
<code class="language-csharp">public static class MemberInfoGetting { public static string GetMemberName<T>(Expression<Func<T>> memberExpression) { MemberExpression expressionBody = (MemberExpression)memberExpression.Body; return expressionBody.Member.Name; } }</code>Get variable name:
<code class="language-csharp">string testVariable = "value"; string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);</code>Get parameter name:
<code class="language-csharp">public class TestClass { public void TestMethod(string param1, string param2) { string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1); } }</code>C# 6.0 and higher versions: Use the nameof operator
The operator provides a simpler way to get the name: nameof
The above is the detailed content of How Can I Retrieve Variable or Parameter Names in C#?. For more information, please follow other related articles on the PHP Chinese website!