Give a class auto implemented properties and initializing constructors in C#
Typically you implement a public property with a private variable known as the property's "backing variable" or "backing store." You then use property procedures to give the program access to the private variable.
The following code shows how a Person class might implement a FirstName property.
private string _FirstName;Philosophically this provides better encapsulation than simply declaring a public FirstName variable 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 is 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 that code that doesn't really do much.
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName { get; set; }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)The example program uses the following code to easily initialize an array of Person objects.
{
FirstName = firstName;
LastName = lastName;
}
Person[] people = new Person[3];See also:
people[0] = new Person("Jethro", "Tull");
people[1] = new Person("Pink", "Floyd");
people[2] = new Person("Lynyrd", "Skynyrd");
- Initialize arrays, lists, and class instances in C#
- Override a class's ToString method to allow controls such as ListBox to display objects in C#


Comments