Give classes auto implemented properties and initializing constructors in C#

classes with auto implemented properties

Giving Classes Auto Implemented Properties

Typically classes implement a public property with a private variable known as the property’s “backing field” or “backing store.” You then use property procedures to give the program access to the private variable. For example, the following code shows how a Person class might implement a FirstName property.

private string _FirstName;
public string FirstName
{
    get { return _FirstName; }
    set { _FirstName = value; }
}

Here the variable _FirstName is the backing field. The FirstName property’s get and set accessors simply return and set the value in _FirstName.

Philosophically this provides better encapsulation than simply declaring a public FirstName field, but in practice it’s not that big a deal. There are some technical differences, but for most programs the difference is small.

To make using this kind of simple property easier, where there’s no additional logic, C# lets you build auto-implemented properties. The following code creates an auto-implemented LastName property. The result is similar to that of the FirstName property but without all of the extra code that doesn’t really do much.

public string LastName { get; set; }

Giving Classes Initializing Constructors

An initializing constructor is simply a constructor that takes parameters and uses them to initialize the new object. The following constructor initializes a Person object’s FirstName and LastName properties.

public Person(string firstName, string lastName)
{
    FirstName = firstName;
    LastName = lastName;
}

The example program uses the following code to easily initialize an array of Person objects.

Person[] people = new Person[3];
people[0] = new Person("Jethro", "Tull");
people[1] = new Person("Pink", "Floyd");
people[2] = new Person("Lynyrd", "Skynyrd");

See also:


Download Example   Follow me on Twitter   RSS feed




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.

This entry was posted in classes, OOP and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *