In the past, for a class member, if we wanted to define it as a property member, we had to define a private member variable first. For example, for the Product
class, we can define a property, ProductName
as follows:
private string productName; public string ProductName { get { return productName; } set { productName = value; } }
This may be useful if we need to add some logic inside the get/set
methods. But if we don't need to, the above format gets tedious, especially if there are many members.
Now, with the new version of C#, the above property can be simplified into one statement:
public string ProductName { get; set; }
When Visual Studio compiles this statement, it will automatically create a private member variable productName
, and use the old style's get/set
methods to define the property. This could save on lots of typing.
Just as with the new type var
, the automatic properties are only meaningful to the Visual Studio 2008 compiler. The compiled assembly is actually a valid .NET 2.0 assembly.
Interestingly, later on, if you find you need to add logic to the get/set
methods, you can still convert this automatic property to the old style's property.
Now, let us create this class in the test project:
public class Product { public int ProductID { get; set; } public string ProductName { get; set; } public decimal UnitPrice { get; set; } }
We can put this class inside the Program.cs
file, within the namespace, TestNewFeaturesApp
. We will use this class throughout this chapter.