Home >Backend Development >C++ >How Can I Get the Name of a Variable or Parameter in C#?

How Can I Get the Name of a Variable or Parameter in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-27 04:11:081014browse

How Can I Get the Name of a Variable or Parameter in C#?

Get the variable or parameter name in C#

In C#, obtaining variables or parameter names can be implemented through multiple methods.

C# 6.0 Solution:

For the previous version of C# 6.0, you can use the class to retrieve membership name:

MemberInfoGetting Get variable name:

<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 parameter name:

<code class="language-csharp">string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);</code>

C# 6.0 and above solutions:

<code class="language-csharp">public class TestClass
{
    public void TestMethod(string param1, string param2)
    {
        string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
    }
}</code>

In 6.0 and higher versions, The operational symbol simplifies this process:

The operational character can be used for parameters, variables and attributes. nameof

The above is the detailed content of How Can I Get the Name of a Variable or Parameter in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn