Home >Backend Development >C++ >How Can I Retrieve Variable or Parameter Names in C#?

How Can I Retrieve Variable or Parameter Names in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-27 04:09:09186browse

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

Before C# 6.0, it is recommended to use a 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

In C# 6.0 and higher versions,

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!

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