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;
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}

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 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)
{
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:

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.