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
Release: 2025-01-27 03:57:09
Original
931 people have browsed it

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>
Copy after login

Get parameter name:

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

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template