WEBINAR:
On-Demand
Application Security Testing: An Integral Part of DevOps
Automatic Properties
In object-oriented programming, it's good practice not to expose your member variables as publicly accessible. Instead, wrap them using properties so that you can impose business rules on them. For example,
Listing 1 shows the definition of the
Contact class containing two properties
Name and
YearofBirth.
There are some conditions to check for when setting the YearofBirth property, while there are none for setting the Name property. In fact, most of the time, you probably won't have any rules for setting the properties. When this happens, defining the get and set statements is superfluous. In C# 3.0, properties that don't need any rules can simply be defined using a feature known as automatic properties. The following is a rewrite of the Contact class using this feature:
public class Contact
{
uint _YearofBirth;
public string Name {get; set;}
public uint YearofBirth
{
get { return _YearofBirth; }
set
{
if (value >= 1900 && value <= 2008)
_YearofBirth = value;
else
_YearofBirth = 0;
}
}
}
Now, there's no need for the private member variable
_Name. The C# compiler will automatically generate its own private member variable to store the name. One advantage to using this feature is that, in the future, when you need to apply your business rules to the setting of
Name properties, you can simply modify the
get and
set statements directly without affecting the external components using this class.
Object Initializers
Generally, there are two ways in which you can initialize an objectthrough its constructor during instantiation, or by setting its properties individually after instantiation. Using the Contact class defined in the previous section, here is one example of how to initialize a Contact object:
Contact c1 = new Contact();
c1.Name = "John";
c1.YearofBirth = 1980;
C# 3.0 provides a third way to initialize objectswhen they are instantiated. Here's an example:
Contact c1 = new Contact { Name = "John", YearofBirth = 1980 };
In the code above, instantiating the
Contact class also directly sets its properties. Remember not to confuse the object initializer with a class's constructor(s). You should continue to use the constructor (if it has one) to initialize the object.
Listing 2 the following modification of the Contact class which has a constructor that takes in a string.
During instantiation, you can pass a string to the constructor while simultaneously using the object initializer to initialize the YearofBirth property:
Contact c1 = new Contact("Wei-Meng Lee") { YearofBirth=1980 };
The object initializer is useful when you want to initialize an object's properties at the time of instantiation.