[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Give classes auto implemented properties and initializing constructors in C#

classes with auto implemented properties

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; }

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");

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.