0

When lamda expression is passed as a parameter,how to get the property name as string? Here is the code for better explaination.

    public static class StringExtension
    {
        public static void ShowPropertyName<T>(this string s, Func<T, object> func)
        {
            // show the property name, which is string "id" or "name"
            // how to get the property name here???
            Console.WriteLine("The original string is " + s);
            Console.WriteLine("The property name...");
        }
    }

    class Member
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            string s = "Hello";
            s.ShowPropertyName<Member>(m => m.Id);
        }
    }

Inside ShowPropertyName, how to get the passed in property name? When s.ShowPropertyName<Member>(m => m.Id), it should get string "Id" and when s.ShowPropertyName<Member>(m => m.Name), it should get string "Name".

Robin Sun
  • 1,352
  • 3
  • 20
  • 45
  • Something is wrong on SO - a "related question" is actually related to the question... If that duplicate I coped from related question does not answer your question please [edit] the question to make it clear why the related question is not related :) (I.e. "I need to use the `Func` and not an `Expression` because ...") – Alexei Levenkov Aug 16 '23 at 02:58

0 Answers0