1

I want to display all of the private property.

        static void Main(string[] args)
        {
            var user = new User(5, "cash");
            foreach(var prop in typeof(User).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
            {
                if (prop.GetSetMethod().IsPrivate) //this line goes wrong
                    Console.WriteLine("Private {0} = {1}", prop.Name, prop.GetValue(user, null));
            }

                Console.ReadLine();
        }
    public class User
    {
        public int Id { get ; }
        public string Name { get; set; }
        private string identify { get { return Id.ToString() + Name; } }
        public User(int id,string name)
        {
            this.Id = id;
            Name = name;
        }
    }

Exactly ouput:throw exception System.NullReferenceException
Expected output: Private number=3

  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Franz Gleichmann Jun 23 '22 at 07:30
  • also: look at your classes properties - some _do not have_ a setter method. so it's only to be expected that `GetSetMethod()` returns null. – Franz Gleichmann Jun 23 '22 at 07:32
  • 2
    From the [documentation of `GetSetMethod`](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.getsetmethod?view=net-6.0): (Returns) "The MethodInfo object representing the Set method for this property if the set accessor is public, or null if the set accessor is not public." – Jon Skeet Jun 23 '22 at 07:32
  • I found the solution, if I change to ```prop.GetGetMethod(true).IsPrivate;``` then it work – Jr. dective Jun 23 '22 at 07:53

1 Answers1

0

GetSetMethod(bool nonPublic)

GetGetMethod(bool nonPublic)

These methods have overloads with a boolean parameter that indicates whether a non-public get/set accessor should be returned. true if a non-public accessor is to be returned; otherwise, false.

So you just need to pass true to GetGetMethod or GetSetMethod if you are working with private properties.

*And i believe you need to use GetGetMethod in your case.

Code:

foreach (var propertyInfo in typeof(User).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
    if (propertyInfo.GetGetMethod(true)?.IsPrivate ?? false) {
        Console.WriteLine("Private {0} = {1}", propertyInfo.Name, propertyInfo.GetValue(user, null));
    } 
}
SAY
  • 26
  • 3