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

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

Barbara Streisand
Release: 2025-01-27 04:01:09
Original
567 people have browsed it

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

Get variables and parameters in C#

In C#, access to variables or parameters names are very important for various scenarios, such as error processing and dynamic code generation. Let's discuss how to achieve this:

C# 6.0 Solution:

Before C# 6.0, the solution to obtain the name of the member is to use reflection. Considering the following category, it provides a generic method for searching the name of the member:

To use this method, you can pass a lambda expression that reference variables or parameters of this expression:

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

C# 6.0 and higher version solutions:

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

In C# 6.0 and higher versions, The operator provides a more concise and more efficient method of acquiring member names:

This operational symbol can be used for parameters, variables, and attributes: nameof

The above is the detailed content of How Can I Get the Name of a C# Variable or Parameter?. 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