In this post, I wanted to introduce you to a new feature that is definitely more than welcome in .NET 3.5: auto-implemented properties. Auto-implemented properties are a shorthand notation for declaring simple properties in classes.
Let's say that I'm developing a class representing a student for an educational software package. In the past, I would have defined the class using the following code:
1: public enum Gender {
2: Female,
3: Male
4: }
5:
6: public class Student {
7: private DateTime birthDate;
8: private string firstName;
9: private Gender gender;
10: private string lastName;
11:
12: public DateTime BirthDate {
13: get { return birthDate; }
14: set { birthDate = value; }
15: }
16:
17: public string FirstName {
18: get { return firstName; }
19: set { firstName = value; }
20: }
21:
22: public Gender Gender {
23: get { return gender; }
24: set { gender = value; }
25: }
26:
27: public string LastName {
28: get { return lastName; }
29: set { lastName = value; }
30: }
31: }
This is a lot of code for a simple class. Fortunately, in .NET 3.5, we can reduce this amount of code and make it even simpler:
1: public enum Gender {
2: Female,
3: Male
4: }
5:
6: public class Student {
7: public DateTime BirthDate { get; set; }
8: public string FirstName { get; set; }
9: public Gender Gender { get; set; }
10: public string LastName { get; set; }
11: }
Using auto-implemented properties, the .NET language compiler will automatically generate the simple data fields for the class and implement the getter and setter methods for each property.
The only thing to consider when using auto-implemented properties is that, in the past, inside the methods of my objects I would use the fields instead of the properties when I needed to access the object instance data. When using auto-implemented properties, you will only be able to use the properties in order to get to your object's data, but that shouldn't be any more inefficient because the compiler will most likely optimize the property access.
Technorati tags:
.net,
dotnet
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5