0

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.

Khalos
  • 2,335
  • 1
  • 23
  • 38
Vasiliy
  • 151
  • 1
  • 8
  • I would also like if somebody tipped me how to learn from visual studio null reference exception window (which for example is popped up after running this code) which of the methods in last line causes exception. – Vasiliy Oct 31 '15 at 16:08
  • Sorry, about my mistake of unattention. Forgot to write {get;set} after LastName, i.e. it wasn't a property. Method works fine. – Vasiliy Oct 31 '15 at 16:58

1 Answers1

-1

Sorry, about my mistake of unattention. Forgot to write {get;set} after LastName, i.e. it wasn't a property. Method from the last line works fine

Vasiliy
  • 151
  • 1
  • 8
  • The problem is that when you missed the {get;set;}, the member "LastName" wasn't a "Property" of the class but was a "Field". And that's why the code .GetProperty was falling over with a null exception, as mentioned, such a property didn't exist, it was a Field. – Don Nov 08 '15 at 10:11