I can not understand the operation of the PropertyInfo.GetValue() method.

I needed to check all the properties of the customerOb object (see code below) to null and return true if successful. I did it using this post , but I can not understand this very “how” everything works.

 public class Customer { public string Surname { get; set; } public string Name { get; set; } public CustomerEdit CustomerEdit { get; set; } } class Program { static void Main() { var custumerOb = new Customer(); var isAllPropertiesNull = custumerOb.GetType() .GetProperties() .Select(pi => pi.GetValue(custumerOb)) .All(p => p == null); } } 

So:

 custumerOb.GetType() - это понятно .GetProperties() - это понятно .Select(pi => pi.GetValue(custumerOb)) - это НЕ понятно 

It would be understandable if GetValue() did not accept the parameter:

 .Select(pi => pi.GetValue()) 

And then we kind of get the next property pi and to find out its value, we pass in the (its) method GetValue() an object whose property it is.

I'm confused. Explain please .Select(pi => pi.GetValue(custumerOb)) expression .Select(pi => pi.GetValue(custumerOb)) . What exactly is going on here?

  • one
    pi is a PropertyInfo that is not tied to a specific object, so in order to get the value of a property from a specific object, you need to label this object in some way. In this case, the object from which the property is taken is passed in the first parameter. - Grundy
  • Well, you know the difference between a class and an object? Here is to check the contents of the property you need a specific object - Andrey NOP
  • 2
    Please note that we work not with the object itself, but with its type (type object): custumerOb.GetType() , the same thing if we wrote typeof(Customer) - Andrey NOP

1 answer 1

First we get the type of the object: custumerOb.GetType() .
Then we get all the properties described in this type: GetProperties() . This will return an array of PropertyInfo objects. They refer to the description of the Customer class, but not to an instance of this customerOb class.
PropertyInfo has a GetValue method. But we cannot just get the value of the property from the description of the class in which this property is described. We have to say the property value of which instance of this class we want to get. For this, we pass a specific instance of the class to this method: customerOb .

  • Add more about static properties. - andreycha