13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

216 CHAPTER 8 Cutt<strong>in</strong>g fluff with a smart compilerpublic Location Home { get { return home; } }public Person() { }}public Person(str<strong>in</strong>g name){Name = name;}public class Location{public str<strong>in</strong>g Country { get; set; }public str<strong>in</strong>g Town { get; set; }}List<strong>in</strong>g 8.2 is straightforward, but it’s worth not<strong>in</strong>g that both the list of friends and thehome location are created <strong>in</strong> a “blank” way when the person is created, rather thanbe<strong>in</strong>g left as just null references. That’ll be important later on—but for the momentlet’s look at the properties represent<strong>in</strong>g the name and age of a person.8.3.2 Sett<strong>in</strong>g simple propertiesNow that we’ve got our Person type, we want to create some <strong>in</strong>stances of it us<strong>in</strong>g thenew features of <strong>C#</strong> 3. In this section we’ll look at sett<strong>in</strong>g the Name and Age properties—we’ll come to the others later.In fact, object <strong>in</strong>itializers aren’t restricted to us<strong>in</strong>g properties. All of the syntacticsugar here also applies to fields, but the vast majority of the time you’ll be us<strong>in</strong>g properties.In a well-encapsulated system you’re unlikely to have access to fields anyway,unless you’re creat<strong>in</strong>g an <strong>in</strong>stance of a type with<strong>in</strong> that type’s own code. It’s worthknow<strong>in</strong>g that you can use fields, of course—so for the rest of the section, just read propertyand field whenever the text says property.With that out of the way, let’s get down to bus<strong>in</strong>ess. Suppose we want to create aperson called Tom, who is four years old. Prior to <strong>C#</strong> 3, there are two ways this can beachieved:Person tom1 = new Person();tom1.Name = "Tom";tom1.Age = 4;Person tom2 = new Person("Tom");tom2.Age = 4;The first version simply uses the parameterless constructor and then sets both properties.The second version uses the constructor overload which sets the name, and thensets the age afterward. Both of these options are still available <strong>in</strong> <strong>C#</strong> 3 of course, butthere are other alternatives:Person tom3 = new Person() { Name="Tom", Age=4 };Person tom4 = new Person { Name="Tom", Age=4 };Person tom5 = new Person("Tom") { Age = 4 };Licensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!