03.01.2015 Views

Complete set: Intro to C - Bill Buchanan

Complete set: Intro to C - Bill Buchanan

Complete set: Intro to C - Bill Buchanan

SHOW MORE
SHOW LESS

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

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

10.5 Hiding members<br />

We can hide the properties of our classes so that they may not be directly accessed.<br />

Many object‐oriented practitioners regard this as good practice.<br />

Before protection<br />

public class Country<br />

{<br />

public string name;<br />

public string region=null;<br />

public int area=-1;<br />

public int population=-1;<br />

public long gdp=-1;<br />

After protection<br />

public class Country<br />

{<br />

private string name;<br />

private string region;<br />

private int area;<br />

private int population;<br />

private long gdp;<br />

duction <strong>to</strong> .NET<br />

<strong>Intro</strong><br />

public string Name{get{return this.name;}}<br />

public string Region{get{return this.region;}}<br />

public int Area{get{return this.area;}}<br />

public int Population<br />

{<br />

get{return this.population;}<br />

<strong>set</strong>{this.population=value;}<br />

}<br />

public long Gdp{get{return this.gdp;}}<br />

In this case have hidden the private members – they can only be accessed from<br />

within the Class. We have exposed members with slightly different names. From<br />

outside the class we may refer <strong>to</strong> uk.Name but not uk.name (where uk is a Country).<br />

Also we have made most of these exposed properties read only.<br />

The Population member is writeable – this means we can assign uk.Population just<br />

as we used <strong>to</strong> be able <strong>to</strong> do.<br />

Which of these is permitted from outside the class<br />

int a = uk.population;<br />

string s = uk.Name;<br />

long b = uk.Gdp; uk.Population = 58000000;<br />

Agilent .NET Course: Module 10,page 7

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

Saved successfully!

Ooh no, something went wrong!