Consider the following simple class definition:
//Simple client class used to demonstate |
A constructor has not been explicitly created for this class so the compiler will generate a default, parameterless one for us. This means that an object can be created and properties assigned inthe way that we are currently used to with C#2
//Create a client object using the default constructor Client firstClient = new Client(); //Assign values to the class properties that have public set methods firstClient.Name = "David"; firstClient.Age = 32; firstClient.Height = 124; |
However, with C#3, we are now able to create an object using any of the following methods:
//Construct the object by supplying the client Name Client secondClient = new Client { Name = "Matthew" }; //Construct the object by supplying //the client Name & Age Client thirdClient = new Client { Name = "Sarah", Age = 21 }; //Construct the object by supplying //the client Name & Height Client fourthClient = new Client { Name = "Daniel", Height = 131 }; //Construct the object by supplying //the client Height only Client fifthClient = new Client { Height = 108 }; |
This is essentially identical to creating a client object with the default constructor and then calling each property set method as appropriate. Looking at the disassembled code shows us what isactually happening for these client objects.
Client <>g__initLocal0 = new Client(); Client <>g__initLocal1 = new Client(); |
As the code above shows, each client is constructed using the default constructor and then the property set methods are called as necessary. Of course, we cannot specify a value for IsCurrent when creating a client object because the set property is marked private (as shown in the first code snippet). Trying to do so will generate a compile time error of something like: The property orindexer ‘Blog.Client.IsCurrent’ cannot be used in this context because the set accessor is inaccessible.
Part 4: Implicit types
No comments:
Post a Comment