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

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

Susan Sarandon
Susan SarandonOriginal
2025-01-27 03:57:09939browse

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

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!

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