Home > Backend Development > C++ > How Can I Get a Property's Name as a String in C#?

How Can I Get a Property's Name as a String in C#?

Barbara Streisand
Release: 2025-01-12 07:58:42
Original
326 people have browsed it

How Can I Get a Property's Name as a String in C#?

Get attribute name string

In C# 6.0 and above, you can use the nameof expression to conveniently get the property name as a string. This expression resolves to the name of the property at compile time.

Example:

<code class="language-csharp">string propertyName = nameof(SomeClass.SomeProperty);</code>
Copy after login

This expression evaluates to "SomeProperty" at compile time.

Note: nameof can only be used for attributes, not for members of other types.

Early version of C#

In versions prior to C# 6.0, you can use the following method:

<code class="language-csharp">public string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
    var memberExpression = propertyLambda.Body as MemberExpression;

    if (memberExpression == null)
        throw new ArgumentException("表达式必须是属性lambda表达式。");

    return memberExpression.Member.Name;
}</code>
Copy after login

This method takes a lambda expression representing a property accessor and returns the name of the property.

Example:

<code class="language-csharp">string propertyName = GetPropertyName(() => SomeClass.SomeProperty);</code>
Copy after login

The above is the detailed content of How Can I Get a Property's Name as a String 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