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
Barbara StreisandOriginal
2025-01-12 07:58:42328browse

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>

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>

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>

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!

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