Automatic Properties in C# In the Contact class defined in the previous section, apart from the ID property, the properties are actually not doing much except assigning their values to private members:
public string FirstName { get { return _FirstName; } set { _FirstName = value; } } public string LastName { get { return _LastName; } set { _LastName = value; } } public string Email { get { return _Email; } set { _Email = value; } }
In other words, you are not actually doing any checking before the values are assigned. In C# 3.0, you can shorten those properties that have no filtering (checking) rules by using a feature known as automatic properties . The Contact class can be rewritten as:
public class Contact { int _ID; public int ID { get { return _ID; } set { if (value > 0 & & value < = 9999) { _ID = value; } else { _ID = 0; }; } } public string FirstName {get; set;} public string LastName {get; set;} public string Email {get; set;} }
Now there ’ s no need for you to define private members to store the values of the properties. Instead, you just need to use the get and set keywords, and the compiler will automatically create the private members in which to store the properties values. If you decide to add filtering rules to the properties later, you can simply implement the set and get accessor of each property. To restrict the visibility of the get and set accessor when using the automatic properties feature, you simply prefix the get or set accessor with the private keyword, like this: public string FirstName {get; private set;} This statement sets the FirstName property as read - only. You might be tempted to directly convert these properties ( FirstName , LastName , and Email ) into public data members. But if you did that and then later decided to convert these public members into properties, you would need to recompile all of the assemblies that were compiled against the old class.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|