samedi 31 octobre 2015

why am I getting null value when trying to get a property value based on the name?

I have this code for getting value of the property based on string name of the property

    public class Person
{
    public String LastName;
}    
static void Main()
{
    Person person1 = new Person { Born = new DateTime(1989, 10, 7), FirstName = "John", LastName = "Smith" };
    string propertytoGet = "LastName";        
    object wantedProperty = person1.GetType().GetProperty(propertytoGet).GetValue(person1, null);    
}  

I am getting null reference exception, since GetProperty(propertytoGet) returns null. I have found this solution on stackoverflow, it was marked as an answer, but it doesn't work for me.





Aucun commentaire:

Enregistrer un commentaire