Classes

Adding properties to a class

Now our  Person  class is taking shape, we need to add some properties to it. Properties allow us to add state to our class. State can be anything which needs to be stored by an instance of your class. We can add properties to our class using the following syntax:

using System; public class Person { ...

 

In our example above, we've defined two propertyproperties of type  string , one named  FirstName , the other named  LastName . This will allow us to give a name value to our class, and that will be stored throughout the lifetime of your  Person  instance.

So let's see how we've done that. Firstly we start with another familiar set of keywords:

public string

So, our property will be of type  string  and will be externally available by marking it as  public . Next, we define what the property is called, and then add those braces  {  and  }  again:

public string FirstName { }

One of the big differences between methods of properties, is properties convey the concept of getters and setters. A getter allows a property to be read, whereas a setter allows a property to be written. We're going to extend our above declaration above to define both a getter and setter:

public string FirstName { get; set; }

We place these keywords within the  {  and  }  braces. This apporach to properties is known as automatic properties. It allows us to declare properties without explicitly having to define something called a backing field. A field is generally a private variable declared as part of the class. Here is that same example, but using an explicit backing field:

public class Person
{
    private string firstName;

    public string FirstName 
    {
        get { return firstName; }
        set { firstName = value; }
    }
}

That's a few extra keystrokes! Depending on how you what to manage the internal state of your class, you may decide to use one approach over the other. The explicit approach we've just tried allows us far greater control, but we'll keep it simple for now.

What we'll do next, is combine our  FirstName  and  LastName  properties with our  GetFullName  method:

using System; public class Person { ...

 

In the example above, we've changed our method to return the value of our  FirstName  and  LastName  properties.

Page 9 of 20