So I have a class:
public class Person
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public Person()
{
AddPerson();
}
private void AddPerson()
{
string fn = this.Firstname;
string ln = this.Lastname;
// Do something with these values
// Probably involves adding to a database
}
}
And I have some code that will instantiate an object and add it to the database, returning the the object of type Person:
Person me = new Person()
{
Firstname = "Piers",
Lastname = "Karsenbarg"
};
However, when I debug this, and get to the AddPerson() method, the properties this.Firstname and this.Lastname don’t have anything in them (in this case are empty).
Where am I going wrong?
This is because properties are assigned after constructor is called. Basicaly, this:
is the same as:
Only difference here is syntax. In your case you may want to pass those variables via parametrized constructor (
new Person("Piers", "Karsenbarg")).