You are on page 1of 125

The Minimum You Need to

Know
AboutMonoandQt

RolandHughes

LogikalSolutions

Copyright2011byRolandHughes
Allrightsreserved
PrintedandboundintheUnitedStatesofAmerica
ISBN13 9780982358085
ThisbookwaspublishedbyLogikalSolutionsfortheauthor.NeitherLogikalSolutionsnortheauthorshallbe
heldresponsibleforanydamage,claim,orexpenseincurredbyauserofthisbookandthecontentspresented
withinorprovidedfordownloadathttp://www.theminimumyouneedtoknow.com.

Thesetrademarksbelongtothefollowingcompanies:
Trademark

Owner

Borland

BorlandSoftwareCorporation

C#

MicrosoftCorporation

DEC

DigitalEquipmentCorporation
HewlettPackardCorporation

DECBASIC

HewlettPackardCorporation

Eclipse

EclipseFoundation

Firefox

MozillaFoundation

HP

HewlettPackardCorporation

IBM

InternationalBusinessMachines,Inc.

Java

SunMicrosystems,Inc.
OracleCorporation

KUbuntu

CanonicalLtd.

Linux

LinusTorvals

LotusSymphony

InternationalBusinessMachines,Inc.

Mac

AppleInc.

MySQL

Oracle

Netware

Novell,Inc.

OpenVMS

HewlettPackardCorporation

OpenOffice

SunMicrosystems,Inc.

OpenSuSE

Novell,Inc.

Oracle

OracleCorporation

OS/2

InternationalBusinessMachines,Inc.

RMS

HewlettPackardCorporation

RDB

HewlettPackardCorporation

SourceForge

SourceForge,Inc.

Ubuntu

CanonicalLtd.

Unix

OpenGroup

VAX

HewlettPackardCorporation

Windows

MicrosoftCorporation

Trademark
ZincApplication
Framework

Owner
ProfessionalSoftwareAssociates,Inc.

Allothertrademarksinadvertentlymissingfromthislistaretrademarksoftheirrespectiveowners.Abesteffort
wasmadetoappropriatelycapitalizealltrademarkswhichwereknownatthetimeofthiswriting. Neitherthe
publishernortheauthorcanattesttotheaccuracyofanysuchinformationcontainedherein.Useofaterminthis
bookshouldnotberegardedasaffectingthevalidityofanytrademarkorservicemark.

AdditionalBooksbyRolandHughes
Youcanalwaysfindthelatestinformationaboutthisbookseriesbyvisiting
http://www.theminimumyouneedtoknow.com.Informationregardingupcomingand
outofprintbooksmaybefoundbyvisitinghttp://www.logikalsolutions.comandclicking
theupcomingandoutofprintbookslink.Atthetimeofthiswriting,LogikalSolutions
andRolandHughesofferthefollowingbookseitherinprintoraseBooks.

TheMinimumYouNeedtoKnowAboutLogictoWorkinIT
ISBN139780977086627
Pages:154
Covers logic, flowcharting, and pseudocode. If you only learned OOP, you
reallyneedtoreadthisbookfirst.
TheMinimumYouNeedtoKnowToBeanOpenVMSApplicationDeveloper
ISBN139780977086603
Pages:795
IncludesCDROM
Covers DCL, logicals, symbols, command procedures, BASIC, COBOL,
FORTRAN, C/C++, Mysql, RDB, MMS, FMS, RMS indexed files, CMS,
VMSPhone,VMSMAIL,LSE,TPU,EDT,SORT,andmanyothertopics.This
bookwas handed outbyHPatatechnical bootcampbecause theOpenVMS
engineeringteamthoughtsohighlyofit.
TheMinimumYouNeedtoKnowAboutJavaonOpenVMS,Volume1
ISBN139780977086610
Pages:352
IncludesCDROM
Covers using Java with FMSandRMS indexed files. There isalotofJNI
coding.WealsocovercallingOpenVMSlibraryroutines,buildingwithMMS
andstoringsourceinCMS.

TheMinimumYouNeedtoKnowAboutServiceOrientedArchitecture
ISBN139780977086665
Pages:370
TheNationalBestBooks2008AwardWinnerBusiness:Technology/Computer
CoversaccessingyourMySQL,RDB,andRMSindexedfiledatasilosviaJava
andportservicesfromaLinuxorotherPCfrontend.Alsocoversdesignand
developmentofACMSbackendsystemsforguaranteedexecutionapplications.
TheMinimumYouNeedtoKnowAboutJavaandxBaseJ
ISBN139780982358030
Pages:186
This bookisavailable only asafreePDF. It'ssource files areavailable on
SourceForge andonthebook's Web page. Thisbookismeant toprovide a
muchneededtutorialfortheOpenSourcexBaseJlibrary. Ifyouhavesome
fundamental JavaskillsthisbookcanhaveyoudevelopingyourownxBaseJ
applicationsinamatterofhours.ThexBaseJlibrarywasusedbytheauthorto
createtheFuelSurchargeprojectonSourceForge.
TheMinimumYouNeedtoKnowAboutQtandDatabases
ISBN139780982358054
Pages:474
ThisbookismeanttoprovideamuchneededtutorialonusingQtwithvarious
IDEs and database tools. Most of the books on the market do a great job
showingyoumostoftheGUIfeaturesofQt,butaresadlylackingwhenitcomes
toexplaininghowtouseQtwithdatabases.Itisnotuncommontofindatmost
onechapterinyourfavoriteQtbookandtolearnitiswoefullyinadequatefor
thetaskathand.Thisbookismeanttosolvethoseproblems.WhileQtattempts
toshieldyoufrommanyunderlyingdatabasedifferences,thisbookwillprove
thatitisonlypartiallysuccessfulandyoustillhavetodesignyourapplication
aroundthelimitationsofyourchosendatabase.

InfiniteExposure
ISBN139780977086696
Pages:471
AnovelabouthowtheoffshoringofITjobsanddatacenterswillleadtothe
largest terrorist attack thefreeworldhaseverseenandultimatelytonuclear
war.
There are a number of reviews of this book available online. The first 18
chaptersarealsobeinggivenawayforfreeatBookHabit,ShortCovers,Sony's
eBookstore,andmanyotherplaces.Ifyoucan'tdecideyoulikeitafterthefirst
18chapters,Rolandreallydoesn'twanttodobusinesswithyou.
JohnSmith:LastKnownSurvivoroftheMicrosoftWars
ISBN139780982358061
ApostapocalypsenovelwhichsomemightconsiderthesequeltoInfiniteExposure.IfI
domyjobcorrectly,itshouldpissjustabouteveryoneoff.

SourceCodeLicense
Thisbookisbeingofferedtothepublicfreely,asisthesourcecode.Pleaseleave
commentsaboutthesourceoforigininplacewhenincorporatinganyportionofthecode
intoyourownprojectsorproducts.
Usersofthesourcecodecontainedwithinthisbookagreetoholdharmlessboththeauthor
andthepublisherforanyerrors,omissions,losses,orotherfinancialconsequenceswhich
resultfromtheuseofsaidcode.Thissoftwareisprovidedasiswithnowarrantyof
anykindexpressedorimplied.
Visithttp://www.theminimumyouneedtoknow.comtofindadownloadlinkifyoudon't
wanttoretypeorcutandpastecodefromthisbookintoyourowntexteditor.

Tableofcontents

Introduction
WhyThisBook?
Ihadtoaskmyselfthisveryquestionwhenstartingtowritethisbook.Actually,an
authorshouldreallyaskthatquestionabouteverybooktheywritebutitwasparticularly
importantforthisbook.ThereareoceansofbooksonC#.Therearepondsofbooks
coveringMono.TherearevariousWebsitesdevotedtothepromotionandsupportof
MonoanditsvariousOpenSourceoffshoots.WhyshouldIwriteabookonit?
Believeitornot,Icameupwithaprettygoodanswer.Mostofthebooksoutthere
fallintooneofthefollowingcategories:

RahRahMicrosoft,don'tbotherteachinganything

Languagesyntaxbiblewhichmightbegreatforreference,butnotforteaching.

MeToo regurgitation of the stuff available for free online by professional


authorswhohavetocrankoutatleastsixbooksperyeartoearnaliving.

Thoseofyouwhohavefollowedthisseriesknowthatmybooksneverfallintothose
threecategories.I'vespentover20yearsintheworldofITwithmostofmyyearsasa
realconsultant.Thedifferencebetweensomeonewhocallsthemselvesaconsultantand
arealconsultantcaneasilybeseenontheirresumes.Scanbackoverthepast20+years
andyouwillseethepeoplewhocallthemselvesconsultantshaveworkedatnomore
thanthreecompanies.Onceinthedoortheylatchonlikeaparasiteandtrytobecome
indispensablesotheycanmilkthesiteforallit'sworth. Arealconsultantwillrarely
spendmorethan18monthsatanysingleclientsite,buttheywillbecalledbacktosites
multipletimesovertheyears.Inshort,arealconsultanttravelsfromclientsitetoclient
site picking up information about additional ways of doing things rather than doing
thingsthesamewayfor20+years.

12

Introduction

Whyisthedefinitionofaconsultantimportant?That'ssimple.Mostofthebooks
outthereonMono/C#weren'twrittenbyrealconsultants.Theywerewrittenbypeople
who call themselves consultants. While many will claim to have over 20 years of
experienceinthefield,mostofthemwillhaveoneyearofexperiencerepeated20times
ratherthanhavetraveledalloveranddonemanythings.Youdon'thavetodigdeepin
theirbackgroundstofindoutifthebookyouareabouttobuyisawasteofcashornot,
simplyfliptothesectiononconnectingtoadatabase.(That'sright,therewillbeonly
oneanditmightnotevenconsumeanentirechapter.)Flipthroughthebeginningand
very end of that section. At any point do they point out directly connecting an
applicationacrosstheInternetorfromoutsideofasecuredinternalnetworkisareally
badidea? Iftheanswer tothat question isyes,thebook youarelooking atwas
written byaveteran; nomeansyourbookwaswritten byacommercial author or
someonewithlessthanoneyearofrealexperiencenomatterhowmanyyearsitwas
repeated.
Yes,wewillcoverthattopicyetagainbecauseIseemtobetheonlyonewriting
aboutitandtherestoftheITworldseemstobeappearingon60Minutestryingto
explainwhyyoushouldn'tgotoprisonforwritingthesystemwhichleadtothismonth's
largestidentitytheft.
Whythisbook? BecauseIlivedwhenthishappenedandMicrosoftsureashell
didn't invent C#. I'mtiredofseeingbooksanointMicrosoftfor inventing something
theyjustrenamed,bought,orinthiscase,mostlystole.
Whythisbook?BecauseMicrosoftisquicklydisappearingfromdesktopandback
office environments. Companies which made the mistake of betting on them need
someonetoshowthemalternativesnow,beforeitistoolate.
Whythisbook?BecausemostdeveloperscannotlearnanOOPtoolfromeithera
syntaxreferencemanualoramarketingbrochure.I'mgoingtocontinuedoingwhatthis
seriesdoesandhasbeenacclaimedfor,redevelopingapplicationswithdifferenttoolsso
developerscanstraddletechnologies.

Introduction

13

WhyOpenSuSE?
ItistruethatI'veusedUbuntuandKUbuntuforotherbooksinthisseries.While
thatsetofLinuxdistrosmaybethemostfamous,they'vetakensomeshortcutstotarget
thenowdisappearingNetBookmarketwhichhasestablishedasunsetdateforUbuntuas
well.Thereisarealproblemwiththeirdistributionmethodologywhichisforcingsome
incrediblybaddesigndecisionsintothatdistro.Ifyoumandatethatyourinitiallive
versionfitonasingleCDinsteadofaDVD,youaregoingtomakeanawfullotofbad
decisionsduetothatinitialbaddecision.
OpenSuSecomesonaDVD,orathumbdrive,andinothermethodswhichallowfor
muchmorethanjustasingleCD'sworthofstorage. Becauseofthisyoudon'tseea
differentrelease ofOpenSuSEforeachpotential Linuxdesktop. Notonlyarethese
desktopsallavailableonyourinitialinstallationmedia,theyareactuallytestedtogether.
Icannot tellyouthenumber oftimes Iwasusing oneflavor ofUbuntu butneeded
somethingwrittenforoneoftheotherflavorstomakemylifeeasier,thenhadlotsof
thingsstopworkingcorrectlyoncetheother700MEGwasdownloadedtosupportthe
otherdesktop.Whenyoupostedasupportissue,youwerequitehonestlytolddon'tdo
thatandtheissuewasclosed.
AnotherreasonweareusingOpenSuSEinsteadofUbuntuisthatthesupportpeople
actuallycare. Ihavewastedhundredsofhoursinemailargumentswiththesupposed
powersthatbeinUbuntulandpointingoutmassivetechnicalflawsdueprimarilyto
theirgeneticinability tograsp technicaltopics. Quiterecentlyoneofthesecerebral
giantstoldmetheyweregoingtosimplyclosewithoutcommentbugreportsIwasfiling
about their forcing all things Qt to use database plugins instead of compiled in
connectionsbecausepluginsweremoresecure. TheEnglishlanguagesimplydoes
nothavetheabilitytoaccuratelydescribethedepthofthatstupidity,andthiswasthe
personincharge!Definitelypromotedtotheirlevelofinability!Ididn'taskthem,but
theysuresoundedlikeanMBAfromKeller!Thatlevelofincompetenceisthenormfor
graduatesofthatschoolinmyexperience.

14

Introduction

ForthoseofyouwhodonotcomprehendthesecurityholeOpenSourceplugins
create,imagineifsomeRussianmafiafamily,orChineseTriad,orsomeotherorganized
crimeentitytakesituponthemselvestowriteacustomversionofeachpluginforeach
release.ThecustomversionaddsthefeatureofloggingalltablelayoutsandI/Otothe
tempdirectory,thenqueuingataskatprogramexittotransmitthisinformationtoa
serveroftheirssomewhereontheWeb.
The crime family then donate a lot of time to various Open Source projects
loading these pluginsintothe distributions. Nobody notices anydifference because
theyhaveonlyaddedalogginganddelayedtransmitfeature.Thecrimefamilyendsup
with every record written to every database using those plugins on every system
containingthem.Yes,theyendupwithalotofchickenrecipiesandmusiccatalogs,but,
eventually they start getting the records for various Open Source competitors to
Quicken, QuickBooks, Seible, etc. Now they have current balance and account
informationandpossiblyevenidenties.Allthatisnecessarytostopthisfromhappening
is to statically compile in the database connectivity. Organized crime must then
infiltrateeachOpenSourcepackagetheywantdatafrominsteadofanypackagethat
couldbeinstalledonyourcomputer.Pointsoffailurenowreducedfrombillionstoone.
Inshort,weare usingOpenSuSE because ithasmatured and,regrettably, ithas
closetiestoMicrosoft.YoumightrememberthatNovellcutadealwhichletMicrosoft
sellSuSEserversandgaveNovellabigchunkofcash.PartofthatcashwenttoNovell
producing a bunch of classes providing Linux services to Mono Core libraries. I'm
currentlyusinga64bitversionofOpenSuSE11.4bothtodothisdevelopmentandto
writethisbook.ItisbyfarthestablestandbestthoughtoutversionofLinuxIhaveever
used. Itdoesn'tcurrentlyhavethefanbaseofUbuntu,buttheshineofUbuntu's
initialjustworksmarketingcampaignisstartingtowearoffnowthatmanypeopleare
encounteringthingswhichdon'twork.
Speakingofthingswhichdon'twork,ItriedtomakeitanentiremonthwithFedora
14beforemovingtothelatestOpenSuSE. IrealizeFedorahasitsfans,but,nothing
worked that I really needed and Fedora's desire to force my disks into some LVM

Introduction

15

configurationreallyirkedme.
If you want a more believable explanation, how about this? Ubuntu has begun
ignoringitsuserbaseinordertoclingtosomeearlymarketingdecisions.Fedora14isa
train wreck. OpenSuSE was the last end user desktop on this list:
http://www.ultraedit.com/products/uex.html Ihaveseenthatexactsamelistforother
commercialproductsaswell.Yes,therewillalwaysbehundredsofLinuxdistros,but
therewillonlybeahandfulcompaniesspendingactualdollarsforcommercialproducts.
AtthispointintimeitlookslikeOpenSuSEwillbethesurvivorthreeyearsdownthe
road.
HowC#ReallyCameAbout
AlongtimeagotherewasacompanynamedSunMicrosystems(nowownedby
Oracle Corporation.) Like many computer companies of the day it had proprietary
computerhardwareandoperatingsystems.Unlikemostcomputercompaniesofitsday,
ithaddirectinvolvementwithembeddedsystemsandtosomeextentvideogames.The
embeddedsystems marketwasbecominganexpensivepauper's childandsomehigh
mindedindividualsatSunlookedtosolvethisproblem.Indeed,theycouldnotachieve
theirvisionofInternetconnectedappliancesunlesstheycouldcreateaprepackagedand
readytoprogramembeddedcomputerforonlyacoupleofdollars.
Embedded systems are so prevalent in today's world that most of you cannot
imaginelifewithoutthem. Thatcoffeemakerwhichyouprogramtostartbrewingat
somepointinthemorninghasanembeddedsysteminit. ThatDVDplayerandthe
remote control forit? Yep,bothofthem. Ifyouhappen todriveacar whichwas
builtin the past ten years it has somewhere between dozens and hundreds of self
containedembeddedsystemsonboard.
Let'sconsiderforamomenttheDVDplayerthatretailsfor$40intheU.S. That
thingmostlikelyhasaproductioncostoflessthan$8,includingallpackaging.Howdo
Ifigurethat? Mostretailerspurchaseinventoryviaadistributor,notdirectfromthe
manufacturerandbothofthemwillexpectatleasta$10cutofthat$40listwhichleaves

16

Introduction

about$12perunitprofitforthemanufacturer,lessshippingcosts,warrantyclaims,and
returns.
Justhowmuchdoyouthinktheyactuallyspentontheembeddedsystemsinboth
theplayerandtheremotecontrol?Itwaspennies.Somelittlegeekhadtospendmonths
of their lives burning ROMs, continually shrinking the footprint of an application
whichcontinuallywasgettingnewfeaturesadded. He/shewasn'tcodingwithahigh
levellanguage, butworking intheassemblerlanguageforthechosenCPUtryingto
squeeze everything to the cheapest CPU and smallest chip count. If someone in
purchasinggotabetterdealonadifferentCPU,thelittlegeekhadtostartover.
Theoriginal concept wasanembedded Java processor. Almost everything ona
singlechiponalittlecardwithconnectorpinsforserial,parallel,network,andpossibly
evensomedisplaytypedevice(normallyLEDconnections.) Theunitwouldcomein
severaldifferentflavorsandsizes.ItwouldcontainbothflashROMandactualmemory
sothatitcouldbeupdatedonthefly. Theproductioncostwouldbedrivendownby
sellingbillionsofunits.
Yes, thecurrent embedded system model would still be cheaper, but thismodel
wouldbebothcheapandfast.Codewouldbetransportablebetweendevicessoinstead
oftaking610monthstodevelopthenextversionprogrammerscouldhaveittothe
testinggroupin610days.ThepresenceofInternetcapabilities,nottomentionallof
thatRAMmeantfeatureswhichwereoncesciencefictioncouldeasilybeimplemented.
Ratherthansimplydisplayingsomecrypticflashinglightsorafaultcode,yourwashing
machine couldsignalthemanufactureritneededrepairandwhatpartsitneeded. It
wouldsendalongitsserialnumberandthemessagewouldactuallygettotheservice
department of the vendor who sold it and the service department would call you to
scheduleanappointment.

Introduction

17

Laughallyouwantaboutmywashingmachinedescription.Somehighendluxury
carsalreadyhavethisfeature.Therehaveevenbeentelevisioncommercialpitchingthis
featuretoconsumers.JusthowdoyouthinkOnStarworks?You'veallseenthoseTV
commercialswhereemergencypersonnelaredispatchedautomaticallywhenthevehicle
determinesitwasinvolvedinacollisionwithairbagsdeployed. Thereisaseriesof
embeddedsystemsallcommunicatingtogethermakingthathappen.
Whileitistruewehaveyettogetsuchawashingmachine,wehavegottenother
sciencefictionproducts.WiththeembeddedsysteminaDVRyoucannowpauselive
TVandstart itback upagain. Your DVRcanevenconnect toavideo ondemand
serviceanddownloadmoviesforyoutowatch. DoIevenneedtomentionallofthe
thingsyourcellphonecandonow,besidesmakeaphonecall?
Of course, thefirst cutofJava,which wastobethelanguage processed bythe
virtualmachineintheembeddeddevice,gotwrittenonUnix,thenLinux,thenalotof
other platforms. Sun wanted to test it and get it adopted, so they made it free for
downloading.SpecificationswerepublishedforJVMssoanyonecoulddevelopaJVM
fortheirfavoriteplatform,butSunalsodevelopedtheJVMformanyplatforms. Of
course,itwasthebuiltinInternetclassesandtheabilitytoworkwithinWebbrowsers
thatcausedJavadevelopmenttogooffonamajortangentaddingfeatureafterfeature.
Eventually,bloatbecamesobadthatmultipleeditionsofJavahadtobereleased:

18

Introduction
Edition

Description

JavaCard

Forusewithtinyfootprintsmartcards

JavaME(MicroEdition)

Various packages built by selectively


loadingsupportonlyforthedeviceswhich
arepresentbecauseloadingsupportforall
wouldexceedavailablestorage.

JavaSE(StandardEdition)

RegularPCuse

JavaEE(EnterpriseEdition)

Lots of extra APIs for multitier


clientserverEnterprisedevelopment

Javaoversolditswriteoncerunanywhereslogan,butitstillbecamethemainstay
ofmostWebdevelopment.OnehastorememberthatthiswasduringtheDOTCOM
stockbubblewheneverybodywasgettingrichontheInternet. Microsoftwas(and
stillis)beingleftinthedust.Industryanalystswerestartingtocalculatethenumberof
daysMicrosoftwouldstillbearoundasacompany.
NaturallyMicrosofttookituponitselftowriteitsownJavaVirtualMachinebased
looselyontheSunspecificationsandmoretightlycoupledtotheWindowsplatform.
TheystartedaddingInternetExplorerandWindowsspecificextensionstothecoreVM
andevenbeganproducingexecutablefilesbyfullycompilingandbindingJavasource
code to an executable just like any other language. (Eventually, many different
companiescameupwithmanydifferentwaystocreateselfcontainedexecutablesand
finallyexecutableJARfilesbecamepartofthestandard.)
There were many heated words exchanged in thetrade press between these two
corporations.ThereweremanyhilariousBillGatesparodiesinthetradepressaswell.
Ultimately there was alot oftime and cash spent onlawsuits and Microsoft had to
dropitsMicrosoftJavaVirtualMachine.
http://www.enotes.com/topic/Microsoft_Java_Virtual_Machine

Introduction

19

Whenitcomestobugriddencodethathasalreadybeenpaidfor,Microsoftrarely
throwsanythingaway. SomenotableexceptionswouldbeWindowsVista,Microsoft
Bob,andMicrosoftMoney. (Don'tworryifyouhaveneverheardoftheseproducts,
theywereandstillarespectacularfailuresalongwithZuneandthesoontobeforgotten
XBox360.)MicrosoftBobutteredafewdyinggaspsasClippytheMicrosoftOffice
AssistantandprettymuchprovedtotheworldwhyBobwasneverallowedtoprocreate.
http://www.ask.com/wiki/Office_Assistant
NotlongafterthesettlementwithSun,wesawtheintroductionofC#.Actually,we
sawthefirstintroductionofaproductfromMicrosoftnamedC#. Yousee,forsome
timebeforethattherehadbeenregularmonthlyinstallmentsfrom AlStevensinDr.
Dobb'sJournalhadaC/C++libraryhewascodingcalledCSharpwhichsuddenlyhadto
berenamedDFlatsoC#couldbelaunched.Microsoftmusthavehadtheirdevelopers
spendallof15minutestweakingtheirJavaVirtualMachinetobeC#.
HelloWorld.java
1
2
3
4
5
6
7

public class HelloWorld


{
public static void main(String[] args)
{
System.out.println( "Hello World!");
}
}

roland@linux-c345:~/mega_Mono> javac HelloWorld.java


roland@linux-c345:~/mega_Mono> java HelloWorld
Hello World!
roland@linux-c345:~/mega_Mono>

JusttakealookathowdifferenttheworldiswithC#!

20

Introduction

helloworld.cs
1
2
3
4
5
6
7
8
9
10
11
12

using System;
namespace HelloWorld
{
class Hello
{
static void Main(string[] args)
{
Console.Out.WriteLine("Hello World!");
}
}
}

roland@linux-c345:~/mega_Mono> mcs helloworld.cs


roland@linux-c345:~/mega_Mono> Mono helloworld.exe
Hello World!
roland@linux-c345:~/mega_Mono>

Obviouslytherewereoceansofeffortputintomakingthesetwothingsdifferent.
Onethingwhichreallycorksmeoff,andshouldcorkoffeveryITprofessionalisthe
fact that, even on a Windows platform, the pcompiled code file is given an EXE
extension.OntheDOS/WindowsplatformtheEXEextensionhadbeenusedforyears
toindicateastandaloneprogram.
NowMicrosofthasahostoflanguageswhichexistonlyasfrontendsandpcompile
to the same virtual machine. Of course Microsoft calls this pcompiled version IL
(IntermediateLanguage)andtheirVirtualMachineiscalledCLR(CommonLanguage
runtime.)Thissetoflanguagesandvirtualmachinesiscalledtheircommonlanguage
infrastructure. Since theydidn't wanttocompletely pissofftheAssembly language
freaksoutthere,hardcorebittwiddlersareallowedtocodetheirprogramsdirectlyinIL
iftheywish.
BeforeyougogivingMicrosoftcreditforchoosingtocompiletoanIntermediate
Language,youshouldreaduponjusthowmanyyearstheGNUprojecthadbeendoing
thatwiththeircompilerset beforeMicrosofteveninchedinthatdirection.Aslongas
the intermediate language chosen is robust enough to support all facets of a source
language, you can create a front end for any language you want except COBOL, it

Introduction

21

appears. Two attempts were made at a GNU COBOL compiler then OpenCobol
emerged.http://www.opencobol.org
TherearemanystoriescirculatingoutthereaboutthehistoryofMono.Practical
MonoApressISBN1590595483givesashorttrueasfarasitgoeshistoryonpage
seven.Thenyoufindotherarticleswhichlendalotofcredencetotherumorsoutthere:
http://www.tikalk.com/net/microsoftcontributeMono
WhileMonomayverywellhavestartedasoneman'smissioninlife,oronesmall
company'smission,ithasevolved. TherumorsonehearsnowisthatevenBillGates
hascometotheconclusionMicrosoftwillsoonbenothingbutafootnoteincomputing
historylikeWang,Commodore,andSinger,soheisdesperatelydonatingcashandcode
totheMonoprojecthopingsomeportionofhiscompanywillstillsurvivehim.Yes,
Singer(thesewingmachinecompany)madecomputersatonepoint.
http://www.time.com/time/magazine/article/0,9171,913860,00.html
Novell (now owned by Attachmate) has been actively developing Mono while
activelydevelopingwithitforsometimenow.NovellLinuxDesktop9wasbasedon
Monodevelopment.Thatsaid,thereisalotofupstreamLinuxdevelopmentoccurring
withothertoolsandlimitingthegrowthofMono.Inordertobridgesomeofthatdivide
wearenowseeingMonowrappersandhooksforotherpackagessuchasQt.Insteadof
using Gtk# which only works on Gnome, you can now specify Qt which runs
everywherewithanativelookandfeel,soyouonlyneedausertohaveCoreMono
installedalongwithQt.
Prerequisites
Youneedtohavereadatleastoneofthefollowing:
TheMinimumYouNeedtoKnowAboutJavaandxBaseJISBN139780977086603
TheMinimumYouNeedtoKnowtoBeanOpenVMSApplicationDeveloper ISBN13
9780982358054

22

Introduction
andpreferably

TheMinimumYouNeedtoKnowAboutQtandDatabasesISBN139780982358054
Most oftheprogramming presented inthisseries isbased ontheconcept that a
skilled programmer knowing one of the covered languages can quickly become
functionalinanotherlanguageifwekeepimplementingthesameapplicationsoverand
over again. You might be tired of my Mega Zillionare or Xpns Tracking
applications,butyouknowwhenyougraboneofthesebooksyouaregoingseeoneof
thoseapplicationsandbeuptospeedinnotime.
WhatnoWeb?
I'mnotgoingtocoverWebhere. Iknowthatmostofthetradepressisallgaga
aboutproductswhichcanconnectdatabasesdirectlytotheWeb,butfromabusiness
perspectivethatisjustabouttheworstideaimaginable.If,andonlyif,thedatabaseyou
wishtoexposeontheWebcontains only whatyouconsider100%publicinformation
thenbyallmeans,makeacopyandplacethatcopyoutsideofyourfirewallsoallcan
gettoit.
Mostdatabases donot meetthe100%publicinformationrequirement. Iwillwin
thisargumenteverytime,andnotjustbecauseI'mtheonewritingthebook.Youtellme
thatyouwanttoexposeaMySQLversionoftheinventorydatabasetotheWebfora
catalogorderingsystem. Youswearonyourgrandmother'sgravethatyouwillonly
create inventory tables and only copy inventory information including product
descriptionsandquantities.Isubmittoyouthatin99%ofallcasesyoustilldon'tmeet
therequirement.Doyouunderstandwhy?
Whomaintainsthisdatabase?Whoactuallycreatesit?IfyouareinaFortune500
or above firm, it will beaDBA. Most systems managers and DBAs useanaming
schema or formula for creating passwords. Oh,itwill meet all of the requirements
havingmixedcaseletterswithnumbersandsomepunctuationcharactersinit,butat
somepoint,therewillbeathreeorfourdigitnumberwhichincrementsbyoneeachtime
thepasswordexpires.EachDBAknowswhatthebasepasswordissotheyonlyhaveto

Introduction

23

tryafewtimestogetin. TheproblemisMySQLprovidesitsownusersecurity. A
successfulattackonyourexposeddatabasewouldrevealapasswordand,possibly,the
generationpattern,puttingallofyourdatabasesatrisk.
Scopeofthisbook
WearegoingtoreinventtheMegaZillionareapplicationusingMonoandQt.In
fact,thisbookisgoingtofocuscompletelyonusingQtwithMonooncewegetallofthe
nastysyntaxdetailscoveredinChapter1.UnlikeotherbooksinthisseriesI'mnotgoing
toconnecttomultipledatabasesjusttoshowyouthedifferingsyntax. Wehavedone
thatoftenenoughinthisseries. Instead,Chapter3willtakeonesmallpieceofour
application,thereports,andgeneratethemoverandoveragain.Why?Becausemostof
youwanttoreadreportswhichlooklikethis:

24

Introduction

Illustration1:ReportExample1

25

Introduction

Youwantfancyheadings,multiplefonts,andnicegraphicallinessegregatingthe
data.Ifyourreportswillbereadbytoday'sMBAs,theycan'treadanythingoverhalfa
pagewithoutapicture,preferablyonesentenceforeverypicturejustlikeachildren's
book.
WhilemostITprofessionalsandbusinessuserswhojustneedthedataaremorethan
willingtoacceptareportwhichlookslikethis:
8/27/2011 3:18:40 PM
Elm
46
51
53
48
52
05
27
39
12
36
17
25

Hits
49
48
47
47
47
45
45
45
45
44
43
43

Most Regular Hits


Since
21
11
5
6
12
2
3
7
4
13
1
11

AveBtwn
8.170
8.370
8.578
8.578
8.578
9.023
9.023
9.023
9.023
9.262
9.512
9.512

MaxBtwn
30
24
30
42
27
45
67
36
40
31
30
27

Page 0001
LongestSeq
2
5
3
2
3
2
2
2
3
2
2
2

Today'sMBAssimplycannotfunctionwith1970sstateoftheartoutput.
No,I'mnotgoingtothrowboththeapplicationandwritingfancyreportsatyouin
onechapter.Existingcodetogeneratefancyschmancyreportsiscumbersomeandnot
welldocumented.Manypeoplepurchasecommercialthirdpartylibrariesorusesome
oftheOpenSourcebasedQtreportwritingtoolstopickandpointvariousreportsfrom
databases.Chapter2willgiveyoustartoftheart1970stextfilesthatneedafixedwidth
font(oroldfashionedlineprinter)tolineupcorrectly.
Chapter3willcoverthefancyschmancyreports.Don'tworry,thiswon'tbeashort
chapter.ReportsistheoneareawhereitseemsQtdeveloperstookthespaghetticooking
approach,theythroughabighandfulofnoodlesupagainstthewallandkeptallthat
stuck. Thereisnotjustonemethodoronefileformatsupportedbythetextbrowser
class.YoucanfeeditHTML,PDF,Postcript,andevenOpenDocumentFormat.Qtalso
providessomedocumenttransformationfunctionalityinthatyoucancreateaPDFfrom

26

Introduction

whateveriddisplayedinyourtextbrowserclass.Wewilllookatallofthisinwhatwill
beaveryinvolvedChapter3.
Finally,thisbook,likemostintheseries,willincludethechapteritisfamousfor,
Ruminations.NeedIsaymore?

Chapter1

Fundamentals

1.1 TheConfusionYouFeelisDeliberate
WhenOOP(ObjectOrientedProgramming)wasjustagleamintheeyeofsoftware
researcherstheyneededtofindawaytoforceitdownthethroatsofassemblyhacking
programmerseverywhere.Chadcomeontothemarketasawidelyacceptedlanguage,
mainlybecauseitallowedassemblylevelhackerstoexercisenearlycompletecontrol
overacomputerwhileusingahighlevellanguage.MostCcompilersevensupported
the __asm{} directive which allowed highly skilled assembly programmers to drop
assemblycodeintothemiddleoftheirCprogram. (Onceoptimizationwasturnedon
thiswasanincrediblybadidea,but,itdidn'tstopsomefromtrying.)So,ifyouwanted
toforceOOPdownthethroatsofprogrammers,thebestwaytodoitwastocreatean
OOPlanguagenamedafter,andmostlycompatiblewithC.
Intruth,thecreatorofthelanguagedidn'tcreateacompilerforitinitially.Instead
hecreatedCfrontwhichtranslatedC++sourceintoCsourcebeforecompilingtheC
source.http://weseetips.com/tag/cfront/OnceC++movedsufficientlyawayfromC,in
particularwithexceptionhandling,therewasnoreasontocontinueworkingonit.By
thattime,actualcompilerswereoutonthemarket.
Because of the low level aspect of C, and by extension C++, we had a lot of
portability and hardware issues. LITTLE_ENDIAN and BIG_ENDIAN issues
constantlyrearedtheirheadsalongwithstandarddatatypesizesoneachmachine.
(LITTLE_ENDIANreferstoarchitecturesthataddresstheleastsignificantbytewhile
BIG_ENDIANreferstoarchitecturesthataddressthemostsignificantbyte.)Sizeissues
wereintroducedbymachinesthemselves.MostdesktopcomputersatthetimeofC++
were16bitDOSmachines.32bitdesktopcomputerswerebeingintroduced,butmost
midrangeandmainframemachineswere64bitsormore.

28

Chapter1Fundamentals

Letusnotforgetthefinalinsult:ASCIIvs.EBCDIC.Evenifwecouldsolveallof
theotherlowlevelproblems,westillhaddifferentcharacterencodingschemasbeing
used.
TherearemanydifferentstoriesaboutthecreationofJavacirculatingintheworld.
Yes,we'vealreadycoveredthestoryabouttheembeddeddevicemarket,buthowdid
theycomeupwiththeJavasyntax? MypersonalbeliefthatIwilltaketothegrave
despiteallevidencetothecontraryisthatSunhadabunchofpeopleworkingforthem
who couldn't learn C++. In an effort to get some kind of benefit from hiring these
people,highermindsatSuncreatedJava.ItcontainedabunchofC++syntax,abunch
ofwrapperclassestodothosethingswhichconfusedpeople,and,mostimportantly,it
leftoutthingslikemultipleinheritancewhichreallybaffledmostofSun'semployees.
Of course Sun touted that Java was truly a GOTOless programming language.
Well,theymayhavenukedthewordfromthelanguage,buttheystillimplementedits
functionality.
Javabackersalsotoutedhowthelanguageremovedmultipleinheritance,amassive
sourceofconfusionandbugsformanyC++developers.Well,initiallyitdidn'tprovide
anymachinerytodothisandpeoplestarteddroppingJavaasadevelopmentlanguage.
Oncethathappened,JavasuddenlygotInterfaces.Aclasscouldonlyinheritfromone
otherclass,butitcouldimplementmultipleinterfaces.
WhenMicrosofthadtoquicklyrepackagetheirJavacompilerproduct,theymade
C#straddle manyoftheissuesbetween JavaandC++whileretaining aconfusingly
similarsyntax.Aswithmostthings,thedevilisinthedetails.

29

Chapter1Fundamentals
1.2 DataTypesandComments
SizeorContent

C#/Mono

Java

C++

8bitsigned
128to127

sbyte

byte

Usually char, size of char determined


byCHAR_BITinlimits.h.Couldbeas
small as 4 bits or as large as 16.
Smallest directly addressable memory
unit.
SCHAR_MIN and SCHAR_MAX
determinevaluerange.
Alsostores8bitASCII.

8bitunsigned
0to255

byte

N/A

unsignedchar
UCHAR_MAXdeterminesvaluerange
fromzero.Alsostores8bitASCII

16bitsigned
32768to32767

short
short
int on many platforms. Short int on
char 16bit char 16bit many other platforms. SHRT_MIN
unicode
unicode
and SHRT_MAX determine short
rangewhileINT_MINandINT_MAX
determineintrange.

16bitunsigned
0to65535

ushort

N/A

Could be short int or simply int.


USHRT_MAX determines range from
zero for short and UINT_MAX
determinesrangefromzeroforint.

32bitsigned
2147483648
2147483647

int

int

Could be long or int depending upon


architecture. LONG_MIN and
LONG_MAXdefinerangeforlong.

to

30
SizeorContent
32bitunsigned
0to4294967295

Chapter1Fundamentals
C#/Mono

Java

C++

uint

N/A

Couldbeunsignedlongorunsignedint
depending upon platform.
ULONG_MAXdeterminesrangefrom
zero.

64bitsigned
long
9,223,372,036,854,
775,808

to
9,223,372,036,854,7
75,807

long

longlong,int,orquadworddepending
uponarchitecture.Quadwordmightbe
astructcontaining2longsoramacro
translatingtolonglong.

64bitunsigned

ulong

N/A

Unsigned long long, unsigned int, or


unsigned quadword depending upon
platform.

float

32bit
32bit
signed
IEEE754
floating
pointvalue

Not required by standard to use any


IEEE representation. Controlled by
compilerswitchesinmanycases.

double

64bit
64bit
signed
IEEE754
floating
pointvalue

Not required by standard to use any


IEEE representation. Controlled by
compilerswitchesinmostcases.

boolean

bool
boolean
bool
8bit true Undefined 1byteasdeterminedbythechardata
orfalse
size
type.Canholdeithertrueorfalse.

31

Chapter1Fundamentals
SizeorContent
longdouble

C#/Mono

Java

128bit
N/A
scaled
integer
data type
1.0x10^28
to
7.9x10^28
provides
2829
significant
digits

C++
Twicethesizeofstandarddouble,not
requiredtouseIEEErepresentation.

Mono
provides a
slightly
different
definition
PackedDecimal

Supported Supported Could be native type depending upon


by classes by classes compiler.
ifatall
ifatall.

MostjuniordeveloperswillarguewitheveryanswerIputintheC++columnofthis
spreadsheet. TheyhaveonlyworkedonaWinTelPCplatform,despiteitsoperating
system, so have never encountered the size issues. Dig back online through your
historyandyouwillreadaboutthedeathmarchMicrosoftputitsprogrammersthrough
migratingfromWindows3.1under16bitDOStoa32bitversionofthatapplication
(whichtheynowcallanoperatingsystem.)

32

Chapter1Fundamentals

PackedDecimalandC#Decimalarenightanddaydifferent.Intheearlydaysof
computing IBMcreated anibble basedcharacternumeric datatype andadded direct
CPUsupportforit. Thisdatatypeprovidedforfixeddecimalmathwithoutrounding
errors. Itsavedanimmenseamountdiskspacebackwhendiskstoragewascosting
about $10,000/MEG. Youcan find apretty decent write up onthis data type here:
http://www.simotime.com/datapk01.htm ThedatatypewaswidelyusedwithCOBOL
andDIBOLprogramminglanguages.Itisstillusedtodayinmanybankingsystemsso
youmayhavecausetounderstanditinyourfuture.
PackedDecimalhadsomeissueswiththevalueusedinthelastnibbleforthesign
value.OriginallyhexCwasusedforpositiveandDfornegativetomimicCreditand
Debit.SomeplatformsusedhexAorhexEforpositiveandhexBfornegative.The
hexFvaluewasusedtoindicateunsignedbymanyplatforms.Eachdigitofthevalue
wasstoredina4bitnibblewiththelast4bitnibblebeingreservedforthesign.
+1,234.56wouldbestoredas0123456Cbecausetherearetwonibblesineachbyte
andyouhadtouseafullbyteforstorage. Noticethatthisformatdoesnotstoreany
informationaboutthedecimalpoint.ThisdatatypemadeCOBOLcopylibsamandatory
part of development until Common Data Dictionaries came onto the scene allowing
multiple languages to share the same variable names with the same definitions. A
decimalpointwasalwaysassumedwiththisdatatypeanditspositioncontrolledby
thepictureclause. Whilethisdatatypedoesn'tworkwellwithOOPlanguagesunless
classes are specifically created to deal with it, on hardware which provides native
supportitisboththefastestandmostaccuratenumericdatatypetouse. WithaPIC
9(7)V99 clause you will always get two decimal digits and truncated intermediate
results. With a PIC 9(7)V99 WITH ROUNDING clause you will always get two
decimaldigitsbutallintermediateresultswillberoundedbaseduponthethirddecimal
digit.

33

Chapter1Fundamentals

Decimal,asimplementedbyC#andMonoisadynamicallyscaledintegerdatatype
for use with floating point values. Unlike IEEE floating point values, it preserves
precision.Ifyouaddtwonumberswhicheachhavetwodecimalplacesyourresultwill
havetwodecimalplaceseveniftheresultisanevenintegervalue. Version1ofthe
Monospecificationactuallymappedouthowall128bitsofthisdatatypeweretobe
used.Thespecificationhassincebeenchangedtounspecifiedstoragetoallowforuse
ofalternateIECspecifications.Theonlywaytoreliablyexchangethisdatatypewith
anothersystemistoexportittoastringandconvertthestringonthereceivingside.
Let'stakealookatConstants:
C#/Mono
Must be declared inside of a
classas:
consttypename=value;
can be preceded by access
qualifierlikepublic

Java

Must be declared inside consttypename=value;


ofaclassas:
declaredanywhere.
finaltypename=value;
canbeprecededbyaccess
qualifierlikepublic

helloworld.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

C++

using System;
namespace HelloWorld
{
class Hello
{
const int my_constant = 32;
static void Main(string[] args)
{
Console.Out.WriteLine("Hello World!");
Console.Out.WriteLine( my_constant);
}
}
}

roland@linux-c345:~/mega_Mono> mcs helloworld.cs


roland@linux-c345:~/mega_Mono> Mono helloworld.exe
Hello World!
32

34

Chapter1Fundamentals

HelloWorld.java
1 public class HelloWorld
2 {
3
public final int my_constant = 32;
4
5
public static void main(String[] args)
6
{
7
System.out.println( "Hello World!");
8
System.out.println( my_constant);
9
}
10 }
roland@linux-c345:~/mega_Mono> javac HelloWorld.java
HelloWorld.java:8: non-static variable my_constant cannot be referenced from a
static context
System.out.println( my_constant);
^
1 error

Asthecompilationattemptaboveshows,Javahasaprotectioncrisiswhenitcomes
toconstants. WhyconstantscannotbeplacedinamanagedareaoftheVMwhichis
addressablebystaticmethodsisbeyondme.Tomaketheaboveworkwehavetoinsert
staticintotheconstantdefinition. IntheworldofJava,staticimpliesthatonlyone
instanceofthisitemwillexistandthatitwillexisteveniftherearezeroinstancesofthe
classcontainingit.Tomethatisalotofneedlessburdenonthecomputerandoneofthe
reasonsJavaapplicationsseemtoberesourcehogs.
hello.cxx
1
2
3
4
5
6
7
8
9
10

#include <iostream>
using namespace std;
const int my_constant = 32;
int main( int argc, char **argv)
{
cout << "value of my_constant " << my_constant << endl;
}

roland@linux-c345:~/mega_Mono> g++ -I/usr/include/c++/4.5 hello.cxx -o hello


roland@linux-c345:~/mega_Mono> ./hello
value of my_constant 32

Chapter1Fundamentals

35

BecauseC#startedoutasrebadgedJava,younoticeithasthesamerestrictionfora
constantvaluedeclarationevenifitusesdifferentsyntax.C++ontheotherhand,lets
constbeusedallovertheplace,includingandespeciallyinheaderfiles.Thisfreedom
withconstantshascausedquiteabitofcomplexitytobeaddedtobothcompilersand
linkers.Yousee,thisfreedomallowedtwodifferentproblemstosurface:
1. Sameconstantnamehavingdifferentvaluesindifferentcompilationunits.
2. Sameconstantnamewithsameconstantvalueexistingmultipletimesacrossand
withinacompilationunit.
Thesolutionprovidedbycompilerandlinkerdeveloperswassomethingcalled
constantfolding.Somewereverygoodandsomeweretrash.Somewouldonlyallow
aconstanttobefolded(havealldefinitionsmergedintoone)ifboththenameandthe
valuewerethesame. Othersfoldedtotheveryfirstdefinitionencounterednomatter
what.TheFirstOneinWinssolutionprovidedsomeinterestingdebuggingwhenever
ourconstantsfellintosituationone.
Manydevelopers,myselfincluded overtheyears,willrefertodefinedvaluesas
constantsorcompilerconstants.Javadoesnothaveapreprocessor,soitdoesn'thave
this situation. Both C++ and C#/Mono utilize a preprocessor which allows for
statementssuchasthefollowingtobescatteredaboutthecode:
#define yellow

12

Whileitistruethat12isconstant,itisatextualconstant.Thepreprocessorscans
through the source code replacing all textual instances of yellow with 12 before
feeding the result into the compiler. You have to be very careful with #define
statements. Normally the preprocessor will only substitute when it finds a perfect
match,butperfectisintheeyeofthebeholder.TheruleinC/C++istomakeall#define
namesuppercase.Thishelpsstopcollisionslikethefollowing:
enum my_colors = {red, blue, green, yellow, black, brown, white};

36

Chapter1Fundamentals

Afterpassingthroughthepreprocessorwiththeabovedefinitionitwouldlooklike
this:
enum my_colors = {red, blue, green, 12, black, brown, white};

You might have guessed that the compiler isn't too fond of that. How about
pointers?
C#/Mono

Java

C++

Most value types and


structures can be pointers,
butdeclarationdoesnotput
syntax on variable name,
ratherontypename.
The following declares 3
integerpointers
int*x1,x2,x3;

Only allowed in JNI code,


theJava language doesnot
supportpointers,butifthey
canbeconvertedtoanative
integer type it can store
their value between JNI
calls.

Most value types and


structures can be pointers.
Syntax is on variable at
time of declaration. The
following declares 2
integersand3pointers:
intx1,x2,*x3,*x4,*x5;

MostbookscoveringC#/Monowon'tevencoverpointers.Ifyouthoughtpointers
weredifficultinCorimpossibleunderC++afterclasseswereintroduced,youain'tseen
nothin'yet!Sorry,couldn'tresistthesongquote.Itreallydoesfit.Besidestheunusual
declaration syntax, you have to remember that C#/Mono runs in a pcompiled state
under a VM. Your data moves around. Unlike C++ where the programmer had
complete control over where variables were allocated, C#/Mono offers only fleeting
controlandclassifiesalluseofpointersasunsafe.
char* str = stackalloc char[1024];
MyClass m1 = new MyClass();
. some code to set values here...
fixed ( int* p = &m1.count)
{
more code here
}

Chapter1Fundamentals

37

Above Ishow you the twomethods of pinning amemory allocation toactual


physicalmemorysoapointercanbetaken.Thefirstexampleactuallyallocatesmemory
onthestack,soitisn'tpinned perse. Thelifetimeofthememory islimited tothe
lifetime of the method in which it is defined. There is no way to delete or free
stackallocmemory.
Fixedtemporarilypinsmanagedmemorytoasinglelocationfortheexecutionof
astatement. Asweallknowastatementcanbeasinglestatementorabunchof
statementsenclosedby{}.
Icouldexplainthisabitfurther,but,I'mgoingtodirectyoutopurchaseacopyof
The Minimum You Need to Know About Java on OpenVMS Volume 1 ISBN
0977086615. You can find more information including places to purchase here:
http://www.theminimumyouneedtoknow.com/java_book.html
No,I'mnottryingtoforcethesaleofanotherJavabookdownyourthroatwhenyou
wanttolearnaboutMono,I'mtryingtokeepthisbookfocused.Thatbookisalmostall
JNIcodeanditdealswithalloftheuglydetailsaboutmoving,pinning,andtransferring
memorybetweenJavacodeandC/C++code.Onceyouunderstandthat,youcandelve
intoMicrosoft'snewCLIstrategy(CommonLanguageInterface.)
If you come from a DOS/PC hacker only background, CLI is a big chunk of
information for you to chew. If you come from a real computing platform like
OpenVMS, then you wonder why passing by descriptor was only halfassedly
implemented.Microsoft'sactualbigthinkershaveevenacknowledgedtheplatformthey
arenowtryingtoemulateafterdecadesofdissing:
http://visualstudiomagazine.com/articles/2008/02/01/theendofthelanguagewars.a
spx
http://www.openvms.org/stories.php?story=08/02/17/5922249

38

Chapter1Fundamentals
Note:UnlikeC,youcannotmixpointer andentitydeclarations onthesame

declarationline.UnderC#/Mono,whenyoudeclareint*x1,x2,x3,allthreeofthese
variablesarepointers.UnderC/C++whenyoudeclareintx1,x2,*x3,*x4,*x5,only
x35arepointers.Conversely,ifyouscrewupandusetheMonosyntaxinC++,only
thefirstvariablewillbeapoint.
hello.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

//

The most familiar test program in the world.

#include <stdio.h>
int main()
{
int* x1, x2, x3;
printf( "Hello Word!!\n");
x1
x2
x3
x2

= &x2;
= 6;
= 4;
+= x3;

printf( "%d

%d

%d\n", *x1, x2, x3);

return 0;
}

roland@linux-c345:~> gcc -o hello hello.c


roland@linux-c345:~> ./hello
Hello Word!!
10 10 4
roland@linux-c345:~>

Chapter1Fundamentals

39

Many of you are probably unfamiliar with what is really meant by stack
allocation,especiallyifyouarerecentgraduates.BackintheDOSdays,andevenon
most midrange computers of the day, we had various stacksize=nnnn switches we
coulduseoneitherthecompilerorthelinker. Thesemagicalincantationscreateda
stackinmemoryonnonstackbasedcomputers.Let'snotgotoodeepdownthebunny
hole defining stackbased andnonstackbased. Suffice ittosaythere weren't many
virtual memory operating systems which allowed for dynamic process memory
allocation.Thebigboxeswheremostlyfixedsizebatchregionmachines.Theyhada
fixednumberoffixedsizedregionswhereyourapplicationcouldrun. Theywould
swapoutentireregionsatatimeaspartoftheirprocesschangeover.Theconceptofa
programbeingabletouseonlywhatitneededdidn'texist.
AllAssemblerlanguagesforallmachinesofthedaymadeuseofaprogramcall
stack.Everytimeamethod/functionwascalled,areturnaddress,returnvaluearea,and
variousparameterswere pushed ontothestack.Thefirstthingthecalledmethoddid
waspoppedoffitsparametersandidentifiedwhereitwouldwriteitsresult.Yes,there
weredifferentrulesaboutwhatgotpushedinwhatorderondifferentplatformsandeven
whichdirectionapushwent,but,forthisdiscussion,wedon'tcare.
Someplatformsrequiredthatalldeclared/automaticvariablesbeallocatedonthe
stack immediately upon method/function entry. Other platforms required that you
allocatedallvariablesfromavailablememoryknownastheheap.Tosomepeople,the
onesallocatingvariablesonthestackbecameknownasstackbased. Regardlessof
howvariableswereallocated,itwastheresponsibilityofthecalledfunction/methodto
cleanupthestackuponreturn.
Yes,IknowAssemblerisn'ttaughtintoday'scolleges.It'sapitybecauseeverybody
needs to understand stacks when they start to toy with CLI (Common Language
Interface)orJNI(JavaNativeInterface.)Mostoftoday'sauthorsdon'tevencoverthese
topicsbecausethey'veneverhadtowriteanAssemblerprogramintheirlife.

40

Chapter1Fundamentals

Ifyourprogrameitherpushedpasttheendorpoppedpastthebeginningofyour
allocatedstackarea,mostoperatingsystemswouldkillitandissueanABENDreport
knownasaSTACKDUMP.IfyouknewAssembler,youcouldidentifyexactlywhat
causedyourprobleminamatterofminutesbylookingattheCALLSTACKanddata
leftonthestack.
Wearetakingtimespeakingofthisbecausestackisgenerallyfixedatprogram
startup.OpenVMSandmostLinuxdistributionshavestacksizevaluessetateitherthe
systemortheuserlevel.OnLinuxaprogramcanmakeacalltosetrlimit()tochange
thecurrentstacksizeofthisprograminstance(assumingtheuserrunningtheapplication
hassufficientprivilege.) UnderDOS,thatGUIversionofDOScalledWindows,and
evenOS/2ifIremembercorrectly,eachprogramsetitsownstacksizeatlaunch.
Youneedtounderstandthatstackisaverypreciousresource.Youmayhave8Gig
of RAM in your Linux or Windows box, but it will not be uncommon to see your
executablelimitedtoeither16Kor32Kofstack.Onmanyplatformsstackisallocated
inapsectwhichoccurspriortothebeginningordirectlyaftertheendofwhereyour
programloadedintomemory.
Havingsaidallofthat,stackisbothsimilaranddifferentwhenspokenofintermsof
the C# or Java virtual machines. It's still a very precious commodity not to be
squanderedcarelessly.

41

Chapter1Fundamentals
Arithmetic

C#/Mono

Java

C++

BasicAssignment

Addition

Subtraction

UnaryPlus

+a

+a

+a

UnaryMinus

Multiplication

Division

Modulo

Preincrement

++a

++a

++a

Postincrement

a++

a++

a++

Predecrement

Postdecrement

Math.Pow()

Math.Pow()

pow()

C#/Mono

Java

C++

NOT

AND

&&

&&

&&

OR

||

||

||

ExclusiveOR

InclusiveOR

Operator

Power

LogicalOperators

42
BitwiseOperators

Chapter1Fundamentals
C#/Mono

Java

C++

NOT

AND

&

&

&

OR

XOR

LeftSHIFT

<<

<<

<<

RightSHIFT

>>

>>

>>

UnsignedRightShift

>>>

>>>

PleasenotethatC++doesnothaveanUnsignedRightShiftOperator.Manyarticles
andbooksyoureadwillclassifyunsignedrightshiftasalogicaloperatorbecauseit
forcesunsignedtreatmentofsignedvalues. C/C++programmersachieveanunsigned
rightshiftbycastingthesignedvariabletounsignedpriortoperformingtheshift.
IreallyhatedincludingExclusive/InclusiveORontheLogicaltable,thenshowing
youthesametwooperatorsinthebitwisetable,but,it'sallpartofthelanguageandI'm
certainyouwillfindsomepoorlydocumentedcodewhichmakesheavyuseofthem.
Letmeshowyousomecodeandexplainwhy some developerswillchoosetouse
thesethingsaslogicoperators.

Chapter1Fundamentals
bitwizelogic.cs
1 using System;
2
3 namespace bitwizelogic
4 {
5
class BitwizeLogic
6
{
7
static void Main(string[] args)
8
{
9
int w, y, z;
10
bool x;
11
12
y = 20;
13
z = 30;
14
w = y | z; // bitwize inclusive or
15
Console.Out.WriteLine("Result of 20 | 30 = {0:n}", w);
16
17
y = 20;
18
z = 30;
19
w = y ^ z; // bitwize exclusive or
20
Console.Out.WriteLine("Result of 20 ^ 30 = {0:n}", w);
21
22
int
k, j, m, n;
23
24
k = 27;
25
j = 15;
26
m = 7;
27
n = 3;
28
29
Console.Out.Write( "\nBefore k {0:n} ", k);
30
Console.Out.WriteLine( " j {0:n}", j);
31
x = (k++ == 100) && (j++ == 100);
32
Console.Out.Write("First && test {0:g}", x);
33
Console.Out.Write(" k {0:n} ",k);
34
Console.Out.WriteLine(" j {0:n}", j);
35
36
Console.Out.Write( "\nBefore k {0:n} ", k);
37
Console.Out.WriteLine( " j {0:n}", j);
38
x = (k++ == 28) && (j++ == 16);
39
Console.Out.Write("Second && test {0:g}", x);
40
Console.Out.Write(" k {0:n} ",k);
41
Console.Out.WriteLine(" j {0:n}", j);
42
43
Console.Out.Write( "\nBefore m {0:n} ", m);
44
Console.Out.WriteLine( " n {0:n}", n);
45
x = (m++ == 7) || (n++ == 3);
46
Console.Out.WriteLine("First || test {0:g}", x);
47
48
Console.Out.Write( "\nBefore m {0:n} ", m);
49
Console.Out.WriteLine( " n {0:n}", n);
50
x = (m++ == 7) || (n++ == 4);

43

44
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78 }

Chapter1Fundamentals
Console.Out.WriteLine("Second || test {0:g}", x);
Console.Out.Write( "\nBefore m {0:n} ", m);
Console.Out.WriteLine( " n {0:n}", n);
x = (m++ == 9) | (n++ == 4);
Console.Out.WriteLine("First | test {0:g}", x);
Console.Out.Write( "\nBefore m {0:n} ", m);
Console.Out.WriteLine( " n {0:n}", n);
x = (m++ == 7) | (n++ == 4);
Console.Out.WriteLine("Second | test {0:g}", x);
Console.Out.Write( "\nBefore m {0:n} ", m);
Console.Out.WriteLine( " n {0:n}", n);
x = (m++ == 12) ^ (n++ == 4);
Console.Out.WriteLine("First ^ test {0:g}", x);
Console.Out.Write( "\nBefore m {0:n} ", m);
Console.Out.WriteLine( " n {0:n}", n);
x = (m++ == 7) ^ (n++ == 4);
Console.Out.WriteLine("Second ^ test {0:g}", x);
Console.Out.WriteLine( "after: ");
Console.Out.Write(" m {0:n} ", m);
Console.Out.WriteLine(" n {0:n}", n);
}
}

Pleasepayveryspecialattentiontotheoutputcreatedbylistinglines50and51.
ThisisoneareawherewannabeUberGeeksshootthemselvesinthegroin.OrdinarilyI
wouldsayfoot,but,thistypeofbugtendstoturnupinmedicaldevicesandhighspeed
trading engines where wannabes are trying to shave a few clock cycles and code
themselvessomejobsecurity.Performingmathematicalcalculationsinsideofboolean
expressionsisquitesimplyanunforgivablecodingfoul.Youshouldbefiredinstantly.

45

Chapter1Fundamentals
roland@linux-c345:~/mega_Mono> mcs bitwizelogic.cs
roland@linux-c345:~/mega_Mono> Mono bitwizelogic.exe
Result of 20 | 30 = 30.00
Result of 20 ^ 30 = 10.00
Before k 27.00 j 15.00
First && test False k 28.00
Before k 28.00 j 15.00
Second && test False k

29.00

j 15.00
j 16.00

Before m 7.00 n 3.00


First || test True
Before m 8.00 n 3.00
Second || test False
Before m 9.00 n 4.00
First | test True
Before m 10.00 n 5.00
Second | test False
Before m 11.00 n 6.00
First ^ test False
Before m 12.00 n 7.00
Second ^ test False
after:
m 13.00 n 8.00
roland@linux-c345:~/mega_Mono>

Takeagoodlookatthehighlightedlinesabovewherendidnotchangevalue.
TheCstandardchosetooptimizebooleanexpressionsbyonlyrequiringthecompilerto
executeenoughcodetoprovethebooleantrue. InthecaseofalogicalORcondition
only oneside needs beexecuted. While weashumans may want tobelieve itwill
always be the first test provided, compiler optimization could eliminate the tests
altogetherifoneexpressioncontainsonlyconstants.
SeethesecondhighlightedTrueabove?Thebitwiseoperatorsforceevaluationof
alltestsnotoptimizedaway.Thisiswhyyouwillseemanygeeksusingtheminsteadof
thelogicaloperators.Itisextremelypoorcodingstyletodoit,but,somepeople'skids
neverlearn.

46

Chapter1Fundamentals
Relational

C#/Mono

Java

C++

Equalto

==

==

==

NotEqualto

!=

!=

!=

Greaterthan

>

>

>

Lessthan

<

<

<

Greaterthanor
Equalto

>=

>=

>=

LessthanorEqual
to

<=

<=

<=

Operators

MemberandPointerOperators

C#/Mono

Java

C++

ArraySubscript

[]

[]

[]

Indirection(valueat)

*n

*n

Addressof(seenotebelow)

&n

&n

Memberofobjectpointedtobyn

n>t

n>t

Memberofobject
Valueatmemberpointedtobyn
Valueatmemberofobject

n.t

n.t

n.t

n>*t

n>*t

n.*t

n.*t

Javaeliminatedpointersfromthelanguage.ArraysandenumsinJavaareactually
classessononeoftheusualtrickswith[]areallowed.Wewillcovermoreonarrays
andemumslaterinthischapter.

Chapter1Fundamentals

47

C#(andbyextensionMono)reallybuggeredthingswhenitcomestopointersand
references.YouwillalwaysfeelmassivelyconfusedifyouaremixingandmatchingC#
andC++.Wetouchedonthisearlier,butIneedtoreallybeatitintoyourskullnow.
Takethefollowingdeclaration:
int* a1, b1, c1;

InC#,theabovedeclarationdeclaresthreepointers. InC++thislinedeclaresa
pointer and two integer variables, if your particular compiler allows the int* syntax
whichmostdothesedays.
int x;
int& y = x;

In C++, the above two lines declare an integer variable and a reference to that
integervariable.NoticehowthesyntaxlookseerilyclosetopointerdeclarationsinC#?
Well,itgetsworse.C#doesnotallowyoutophysicallydeclareareference. TheC#
languageenforcestherulesthatallnativevaluesaretypevariablespassedbyvalue
and all object variables are references which need an instance created for them to
refererence. KnowingthisruledoesnotmakethelifeofyourC++programmerany
easier when coding in C#. It also doesn't help when you must hop back and forth
betweenlanguageswhichshareamassiveamountofsyntax.
Nowletusdiscusstheabyssknownascomments.

48

Chapter1Fundamentals
C#/Mono

Java

C++

//singlelinecomment

//singelinecomment

//singlelinecomment

/*multi
*line
*comment
*/

/*multi
*line
*comment
*/

/*multi
*line
*comment
*/

/**XMLcomments
onmultiplelines
*/

/**JavaDoccomments
onmultiplelines
*/

/// XML comments on a


singleline.

Of course there have been many thirdparty and layered attempts to introduce
variouscommenttaggingmethodstoC/C++andJavaovertheyears.Onewhichseems
tospringforthfromtheApplecampisHeaderBrowser.Youcanfindmoreinformation
aboutithere:http://www.headerbrowser.org/TheOpenSourceeffortwithsupportofthe
entire Qt community behind it is a product called Doxygen which handles multiple
languages,includingbothC++andC#/Mono.Youcanlearnmoreaboutthisefforthere:
http://www.stack.nl/~dimitri/doxygen/index.html
Inanycase,ifyouwishtogenerateuseabledocumentationfromyoursourcecode,
youwillspendhours inserting tags into comments andadding comments where you
never once thought about adding them. Just click here to see the test class with
comments: http://www.stack.nl/~dimitri/doxygen/docblocks.html and be sure to click
thelinktheyprovidetoviewtheHTMLgenerateddocumentation.Thisisexactlythe
kindofclassdocumentationonewantstoseeautomaticallygeneratedfromsourcecode
butmostofyouwon'tenterthatmanycommentsforasingleclasseveniftheyput
aguntoyourhead.Whatprogrammersconsidersufficientdochastotelegraphahead
tofindwhattheworldconsidersinadequatedoc.

Chapter1Fundamentals

49

Oneofmyfavoritedocumentationstoriesactuallycamefromanaccountrepfora
consulting firm specializing in providing documentation consultants. Upper
managementcalledtheconsultingfirmintoameetingwiththeleaddevelopertodiscuss
awardingadocumentationproject.Theleaddeveloperwasallpissedoffclaimingthat
themeetingwasawasteofhiscodingtimeandallyouhavetodoislookatthecodeto
figureoutwhatitdoes.Theresponsewaspriceless:Yes,Icanlookatasparkplug
andtellyouthatitisusedforcombustion,but,withoutdocumentation,Icannottellyou
ifthisparticularsparkplugisusedinaBriggs&StrattonlawnmowerengineoraFord
V8.

JUnitwasGod'sgifttoprogrammers.

JUnitwillbringabouttheendofmankind.

Bothofthosestatementsaretrue.JUnitallowsa$400+/hrconsultantwhoactually
understands the business entity the system is being developed for and completely
understands the business requirements to generate a flawless system with less than
onethirdofthetimedevotedtotesting. JUnitallowsthetypical$10/dayillegalalien
consultanttoturninasystemwhichpasses100%ofallunitandautomatedregression
testingyetdoesn'tworkatall.Wewilldiscussmoreabouttestinglaterinthisbook.I
bringitupnowsoyouhaveaframeofreferencetodiscussautomateddocumenation.
Hopefullyyouallwenttothedoxygensiteandsawtheamountofcommentswhichhave
tobeaddedto eachandevery classtogeneratethekindofdocumentationeveryone
expects.
JUnit,JavaDoc,andDoxygenareallbasically thesame. A$400+/hr consultant
createsmiraculousthingsofbeautywiththem;theclassofdeveloperpursuedbytoday's
MBAsproducenothingbuttrainwrecks.

50

Chapter1Fundamentals

It is my professional opinion that all languages will move to the Doxygen


commentingstandard(withthepossibleexceptionofdiehardJavaDocshops.)Thetool
ishighlyportableandalreadysupportsawidearrayoflanguages.Everybodyandtheir
brother wants to have really nice HTML documentation ready for online posting
complete with hyperlinks, menus, and a table of contents. At first they will try to
demandthislevelofdocumentationforfreefromtheirprogrammers.Then,afterthey
see what gets generated from their programmer's comments, they will have to hire
$200/hrtechnicalwriterstogoinandaddDoxygencommentstothecode.
By now you should be understanding that Microsoft well and truly gave the
programming world the short stiff one when they rebadged their
JavacompilertightlycoupledtoWindowsasC#.WearenowatapointwhereIhave
tosplittherestofthisconfusingdiscussionoutintoitsownsections. Itis definitely
okaytotakeabreatherbeforereadingon. Whatweareabouttodiscussnextisquite
nasty.

1.3 StructureandClassConfusion
Theoriginalideabehindastructurewasthatitwouldprovidealogicalgrouping
ofdata.YouseestructwasthenewhoitytoitywordforRECORD.BASICprovided
uswithaRECORDwhich,ironically,wasusedtodeclareastructurewewouldreadand
writetofiles.COBOLprovidedusthe01levelunderneaththeFD(FileDescriptor)to
contain the various record definitions which could be written to an indexed file. C
desperatelyneededawordwhichcouldprovidethislogicalgrouping,but,therewasa
problem.Cwasacheaplanguageusedtowriteanincrediblycheapoperatingsystem.
ThatOStookmassive shortcutsandadoptedsignificantdesignflaws because itwas
neversupposedtoseethelightofdayinthebusinessworld.

Chapter1Fundamentals

51

Unix was supposed to be a single purpose platform which would allow task
switchingandremoteaccessbytechnicians,but,itsoriginaldesignpurposewastoonly
operatetelephoneswitchingstations. Suchasinglepurposecoupledwiththepromise
thiswouldneverbereleasedcommerciallyorrequireanysupportwhatsoeveroutside
ofthecompanyallowedhorrificshortcutstobetakenwiththeOSdesign.Tostartwith,
itreallydoesn'thaveprocesses,ithasthreads,but,wediscussedthatinanotherbookof
thisseries.Moreimportantly,theentireOSkernelwaswrittenwithoutembeddingthe
conceptofarecordastheprimarylogicalIOunit.Yes,itsupportedblocksforphysical
IO,buttherewasnologicalIOconcept. Theonlybuiltinfilestorageconceptwasa
stream. Tothisday thisissue still causes massive multiuser headaches and disaster
recoveryproblems.Ifsomeonehadn'tfinallywrittenarelationaldatabaseforfirstUnix,
thenLinux,neitheroperatingsystemwouldbetheleastbitusableinthebusinessworld.
ThefirstwarttoappearintheClanguageduetothismassivedesignflawwasthe
structkeyword.Thepowersthatbedidnotwanttopointoutsuchamassivedesign
flawatatimewhen90%ofallcriticalbusinessdatawasstillstoredineitherindexed
filesoronmagnetictape,inrecordformat.HadtheyintroducedtheRECORDkeyword
thefirstthingtheITcommunitywouldhavesaidisGreat,howdoIdeclarekeysand
connectthistoafileforpermanentstorage?
Colleges,whobynowhadcopiesoftheoperatingsystemwhichwasn'tsupposedto
see the light of day and the compiler for the language developed to only write that
operatingsystem,startedteachingDataStructurescourses.Studentswererequiredto
oohandaahathowyoucouldcreatelinkedlistsanddoublylinkedlistsbyembedding
nextandpreviouspointersinsideofadatastructurewhichwasnaturallyimplemented
viathestructkeyword.ITprofessionalsonceagainsaidGreat,howdoIdeclarekeys
andconnectthistoafileforpermanentstorage?
LetmeveeroffamomenttoexplainwhatImeantwhenIsaidCwasacheap
language.ThosewhoknowmeknowIhaveworkedfordecadesusingC,butitwasand
stillisacheaplanguage.

52

Chapter1Fundamentals

Cwasdesignedtobeonelevelaboveassemblylanguagewhenitwasoriginally
implemented. Thecore language itself provides almost nofunctionality. What you
believetobethecorelanguageisasetofextensionlibrariesandheaderfileswhich
havebeenaddedtothelanguageandbecamepartoftheANSICstandardatsomepoint.
Theworld'smostfamousCprogram,hello.c,doesn'tevenworkwithouttheextensions.
hello.c
1
2
3
4
5
6
7
8
9
10

//

The most familiar test program in the world.

#include <stdio.h>
int main()
{
printf( "Hello Word!!\n");
return 0;
}

roland@linux-c345:~> gcc -o hello hello.c


roland@linux-c345:~> ./hello
Hello Word!!
roland@linux-c345:~>

Incaseyoudon'tknowthislittlebitofLinuxlore,ifyoudon'tspecifyanoutput
name when calling gcc, your executable file, if created, will be named a.out. This
naming existsforhistoricalreasonswhichfewer andfewer peopleremembereach
year.ThisisyetanotherexampleofhowUnixandLinuxweredesignedtobecheap,
ratherthanbusinessclass,platforms.
COBOLandBASICare,bycontrast,expensivelanguages.Bothoftheselanguages
notonlyprovideforcomputationalcomplexity,butcomebundledwiththemajorityof
I/Ooriginallyneededfortheirday.
HELLO.BAS
1
2

10 PRINT Hello World!


32767 END

Dependinguponthecompileryouuse,theENDstatementmaybeoptional.

Chapter1Fundamentals

53

HELLO.COB
1
2
3
4
5

IDENTIFICATION DIVISION.
PROGRAM-ID. hello.
PROCEDURE DIVISION.
DISPLAY "Hello World!".
STOP RUN.

Yes,COBOLmaintainsitspositionastheword'smostwordycomputerlanguage,
evenwiththisexample,andonlygetsworsewithfutureexamples,but,youshouldbegin
tosee,onedoesn'tneedtobringoutsidelibrariesinforcorefunctionality.Ifyouhave
notreadTheMinimumYouNeedtoKnowtoBeanOpenVMSApplicationDeveloperat
thispoint,Isuggestedyoufindacopyandatleastreadupontheaccessingofindexed
files.
C was crippled right out of the gate. Because it was originally conceived as a
portableassemblylanguagewhichwouldbeusedtoportaproprietaryOSusedtorun
communicationsswitches,itwasn'tgiventheconceptofarecord.Sadly,Microsoftand
otherflavorsofDOSalsodidn'thavetheconceptofarecordbuiltintotheOSeither.
This meant that C, which didn't require support for indexed file systems like other
languages,portedeasilytotheplatform.Oncepeoplegotboredwithwritinghelloto
the monitor, very expensive indexed file and database libraries surfaced. Many
flavorsofXbaseshowedupandweremostlyincompatiblewitheachother,thoughthey
hadoverlappingcapabilities.(YouneedtoreadTheMinimumYouNeedtoKnowAbout
JavaandxBaseJtogetmoreinformationonXbasefileformatsandhistory.)
Whenthevariousstandardscommitteesmet,MicrosoftandthevariousUnix/Linux
vendorshowledmercilesslyatthemeresuggestiontheANSICstandardrequiresupport
forindexedfilesliketheHolyTrinityofCOBOLFORTRANBASIC. Vendorswho
werebusybackstabbing,thievingfrom,andsuingeachothertooktimeoutfromtheir
busydaysofmayhemtoprovideaunifiedfrontagainstsuchsupportinthelanguage
standard.ThisunifiedfrontcontinuedonintotheANSIC++standard.SinceJavawas
basicallywrittentoallowprogrammerswhocouldn'tcomprehendC++toprogram,it
continuedthetradition.Needlesstosay,whenthefreshcoatofpaintwasappliedtoJava

54

Chapter1Fundamentals

andMicrosoftrebrandeditC#thatfreshcoatofpaintdidn'tincludesupportforindexed
filesystemswhichMicrosoft'spatheticexcusesforoperatingsystemscouldn'tnatively
provide.
Mostenduserandsmallbusinessdatastorageneedscaneasilybemetbyanative
indexedfilesystem.ManyofyouhavetheopinionthatanSQLinterfacemeansyouare
usingarelationaldatabase,andyouwouldbewrong. WhilethingslikeMySQLand
SQLite provide SQL interfaces to C/C++, Java, and C#/Mono, they don't normally
providearelationaldatabase. OnmostplatformsMySQLdefaultstoitsownindexed
filesystem.SQLitehasbecomeamasteratobfuscatingjusthowitstoresthings:
S
QLi
t
ei
sa
ne
mb
e
d
d
e
dS
QLd
a
t
a
b
a
s
ee
ng
i
ne
.
Unl
i
k
emo
s
to
t
he
rS
QLd
a
t
a
b
a
s
e
s
,
S
QLi
t
e
d
o
e
sno
tha
v
eas
e
p
a
r
a
t
es
e
r
v
e
rp
r
o
c
e
s
s
.S
QLi
t
er
e
a
d
sa
ndwr
i
t
e
sd
i
r
e
c
t
l
yt
oo
r
d
i
na
r
yd
i
s
k
f
i
l
e
s
.A c
o
mp
l
e
t
eS
QL d
a
t
a
b
a
s
ewi
t
h mul
t
i
p
l
et
a
b
l
e
s
,i
nd
i
c
e
s
,t
r
i
g
g
e
r
s
,a
nd v
i
e
ws
,i
s
c
o
nt
a
i
ne
di
nas
i
ng
l
ed
i
s
kf
i
l
e
.Thed
a
t
a
b
a
s
ef
i
l
ef
o
r
ma
ti
sc
r
o
s
s
p
l
a
t
f
o
r
m -yo
uc
a
nf
r
e
e
l
y
c
o
p
yad
a
t
a
b
a
s
eb
e
t
we
e
n3
2
b
i
ta
nd6
4
b
i
ts
y
s
t
e
mso
rb
e
t
we
e
nb
i
g
e
nd
i
a
na
ndl
i
t
t
l
e
e
nd
i
a
n
a
r
c
hi
t
e
c
t
ur
e
s
.
Youcanfindtheabovequoteat: http://sqlite.org/about.html. IcantellyouthatI
haven'teverfoundarelationaldatabaseoranindexedfilesystemwhichwouldletyou
copy a single file data set between 32bit and 64bit systems, let alone between
bigendian and littleendian. I will hazard a guess that there is some textonly
XMLbasedstoragegoingoninsideofthosefiles,butIhaven'tlookedtobecertain.In
anyevent,itisnotabinaryrelationaldatabaseyouareusing.AsIsaid,mostenduser
through small business data storage needs can easily be met by today's indexed file
capabilities.FormoreonthistopicyouneedtoreadTheMinimumYouNeedtoKnow
AboutQtandDatabases.
Beforethesimplestructmorphedoutofjustbeingarecorddefinition,itgaveusno
endofulcers,atleastintheC/C++world.Thoseulcerswereallduetoproblemscaused
bymemory alignment chosenbyeachcompiler. This created allkindsofproblems
whentryingtostoredataondiskforanotherprogramtoread. Eveniftheprograms
wererunningonthesamecomputer,butusingdifferentmemorymodels.

Chapter1Fundamentals

55

During the days of DOS/Windows, C compilers could compile code using the
Compact,Small,Medium,andLargememorymodels.(Compactwasanoddityusedfor
creating .COMbinaries.) This architecture alsousedaSEGMENT:OFFSET typeof
memory addressing rather than the linear memory addressing used by some other
platforms.Thesizeofdatatypes,inparticularpointers,changedwhencompilingwith
differentmemorymodels.Thedefaultalignmentalsochanged.
struct {
char
c1;
long
emp_id;
char
first_name[35];
char
last_name[45];
short int
age;
} emp_age, *emp_age_ptr;

Thenoviceprogrammerwouldexpecteachoftheseitemstobeplacedbacktoback
in memory without any intervening gaps. If you were working with the Compact
memorymodel,thecompilerwouldevenreinforcethisbeliefbecausethedefaultfor
mostcompilerswaspack(1)oralign(1)withthatmemorymodel.Theonesignifiedbyte
alignment. From a performance standpoint, this was inefficient. Most desktop
computersofthedayworkedwellwithlongword(orlongor4byte)alignment,butonly
certainmemorymodelsallowedthattohappen.Thedefaultstructurealignmentchanged
witheachmemorymodel.Unlessyouadded#pragmastatementsaroundyourstructure
definitionstocontroltheircreation,yougotwhateverthedefaultwasatthetimethe
compilergottoyourstructuredefinition.
Aslongasyouwereworkingwiththisonlyinmemoryandnotdoingpointermath,
thesizeandalignmentofthestructuredidnotmatter.Whenyoudidpointermathyou
hadtousetheCcompileroperatorsizeof()togetthecorrectsizeofthestructurebefore
movingyourpointer.Thewheelscameoffthecartwhenyouwrotethisinformationto
diskandanotherprogram,compiledwithdifferentalignment,triedtoreadit.Thesize
ofthestructureitwantedtousewouldbedifferentandverybadthingswouldhappen.

56

Chapter1Fundamentals

WhenC++camealongandtheCfrontprogramtranslatedC++sourceintoCadding
functionsformethodsandpointersfor this,thingsgotreallyuglyintheworldofthe
struct.Eventually,theC++languagemovedfarenoughbeyondthecapabilitiesoftheC
languagethatrealcompilershadtobeusedandthetranslatorwasabandoned.
http://en.wikipedia.org/wiki/Cfront
I'mtakingyoudownthisrabbitholebecauseyouneedtobeawareoftheproblems
beforeyoucanunderstandwhysomethingswhichseemlikespectacularfailuresstill
existinalloftheselanguages. Theywereallattemptstoworkaroundthisproblem.
Yes,eventhecreationofMySQLandSQLitewereattemptstoworkaroundthisvery
problem. While it may be difficult to understand with SQLite, it should be readily
apparent when you visit the MySQL site and look at the possible responses for the
SHOWENGINEScommand.

Illustration2:MySQLShowEngines

In the early days of C/C++, each of these engines would have had their own
proprietary C/C++ header files and library interface calls. Each would have used
function names which were completely incompatible with the other, not to mention
completelydifferentparameterorderandreturnvalues.ByplacingtheMySQLserver
enginebetweenthedataandtheapplication,younotonlygainedfilesharing(which
really never existed on DOS/Windows), but you gained a unified interface. Your
applicationissuestheSQLINSERTcommandandMySQLhastofigureouthowtoget

Chapter1Fundamentals

57

thedataintotheindexedfile.
Pleasenotethatonlyoneenginecurrentlysupportstransactions. Manypeople
drawtheconclusionthatifyoureadandwriteviaSQLitmustsupporttransactions.
Nothingcouldbefurtherfromthetruth!
OldhandsshouldnotbesurprisedbythepopularityofeitherMySQLorSQLite.
MostofyoushouldremembertheheydayofNovellwhenitsoldafileserverknownas
Netware.WhatthisserverhadoverallotherswastheBtrieveindexedfilesystem.It
handledallofthesharingandprovidedarequesterwhichcouldeithercreateunshared
local files or shared remote files. Netware sold in massive quantities despite its
incrediblyhighpriceandevenhigherbranded/certifiedcomponentprices.Forthefirst
timedesktopcomputershadarobustshareableindexedfilesystem.
Today,wehaveTCP/IPstandardsandOpenSourcedatabaseswhichwillletany
desktopcomputerbecomeadatabaseserverprovidedsomeonewantstoenterallofthe
userIDsandpasswords. It'sabitofabreakfromthefileserverbaseddatabase,but
eventuallyweshallfindahappymiddleground.Havingtohaveadifferentusername
andpasswordforeverydatabaseyouaccessisarealPITA.Oldstyle,centrallyserved
databasesallowedyoutoconnecttoanynumberofdatabasesonceyouwereloggedinto
the server. Many of those server platforms are the highly secure midrange and
mainframeplatformsmostofthePCworldiscallinglegacyandheritage,yetthePC
worldstillcannotreplace.
Ihadplannedonputtinganotheroneofmynicelittletablesinheretoshowyouthe
differences,but,Javadoesn'tallowfororsupportthestructkeyword.TheJavaworld
expectsyoutocreatesimpleclassesinstead.Icanseewheretheycameupwiththisidea
anditisafinefineboottothehead.

58

Chapter1Fundamentals

hello_struct.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

//

The most familiar test program in the world.

#include <stdio.h>
#include <string.h>
struct my_struct {
int a, b, c;
char *the_name_str;
} fred;
typedef struct {
long
emp_id;
char
first_name[35];
char
last_name[45];
short int
age;
} emp_age;
typedef struct {
public: long
emp_id;
private: char
first_name[35];
private: char
last_name[45];
protected: char
dept[10];
public: void fill_in( char *f, char *l, char *d)
{strcpy( first_name, f);
strcpy( last_name, l);
strcpy( dept, d);
}
void display_this() {
printf( " %ld %s %s %s\n",
emp_id, first_name, last_name, dept);
}
} emp_dept;
int main()
{
emp_age a1;
emp_dept d1;
printf( "Hello Word!!\n");
fred.a = 12; fred.b = 13; fred.c = 14;
fred.the_name_str = "test name";
printf( "fred: %d %d %d %s\n",
fred.a, fred.b, fred.c,
fred.the_name_str);
a1.emp_id = 1024L;
strcpy( a1.first_name, "Roland");
strcpy( a1.last_name, "Hughes");

Chapter1Fundamentals
51
52
53
54
55
56
57
58
59
60
61
62
63 }

a1.age = 21;

59

// I wish!!

printf( "a1: %ld %s %s %d\n",


a1.emp_id, a1.first_name, a1.last_name,
a1.age);
d1.emp_id = a1.emp_id;
d1.fill_in( a1.first_name, a1.last_name, "IT");
printf( "d1: ");
d1.display_this();
return 0;

NoticethatIputaCXXextensiononthisinsteadofC.IfyousavethisfilewithaC
extensionandtrytocompileityouwillhavethefollowinghappen:
roland@linux-c345:~> gcc hello_struct.c -o hello_struct
hello_struct.c:20:5: error: expected specifier-qualifier-list before public
hello_struct.c: In function main:
hello_struct.c:57:7: error: emp_dept has no member named emp_id
hello_struct.c:58:7: error: emp_dept has no member named fill_in
hello_struct.c:60:7: error: emp_dept has no member named display_this
roland@linux-c345:~>

ACXXextensionallowsforsuccessfulcompile,link,andexecution.
roland@linux-c345:~> g++ hello_struct.cxx -o hello_struct
hello_struct.cxx: In function int main():
hello_struct.cxx:43:25: warning: deprecated conversion from string constant to
char*
hello_struct.cxx:58:50: warning: deprecated conversion from string constant to
char*
roland@linux-c345:~> ./hello_struct
Hello Word!!
fred: 12 13 14 test name
a1: 1024 Roland Hughes 21
d1: 1024 Roland Hughes IT

I'm not real happy with the change in the C/C++ standard which deprecated
conversionfromstringconstantto'char*',butIhavetolivewithit. BasicallyOOP
poochednormalcomputerarchitectureandcompilerwritershavenotbeenabletocope.
Remember when I told you about the PC memory models earlier in this chapter?
Well, other architectures hadbetter control, they used PSECTs which were Program
Sections inmemory. EachPSECTcould betaggedwithvarious attributes likeRD,

60

Chapter1Fundamentals

WRT,EXEC,RDNLY,etc. ThePCtrieddoingthisinitiallywiththesegments,then
adoptedthePSECTmodel(asbestitcould)forthemultisegmentedmemorymodels.
DuringthedaysofCandotherearly3GLs,ALLconstantswererolledintooneor
morePSECTswhichhadtheRDNLY(ReadOnly)attributeassigned.Compilerwriters
didn'thavetocareaboutwhatyoudidwithastringpointerbecausetheinstantyoutried
towritetoaRDNLYPSECT,theOSwouldkillyourprocesswithanaccessviolation.
Somewhere,inthemiddleofallthis,cameselfmodifyinglanguageslikeLISPand
Forth.Championsofthemcheeredtheselfmodifyinglanguageasalivinglanguage
thusinherentlysecureandmostsuitableforAI(ArtificialIntelligence)work.Therest
oftheITworlddecriedselfmodifyinglanguagesforbeingnondeterministicANDnot
takingadvantageofthehardwareprotectionavailableinthecomputer.Whileyoucan
still find LISP and Forth out there, thankfully, the marketing machine for AI
dramatically oversold whatcould bedelivered intheshort term andself modifying
languageshaveverylittleinthewayofrealdollarsorrealdevelopmenteffortsbeing
thrownatthem.
Regrettably, most of the AI developers and language designers which were cast
aside bytheindustry,managed tojump into jobs atplaceslikeBellLabsandother
research facilities that were coming upwith OOP. Theyperpetuated thisreally bad
practice of self modifying language and carefully disguised it within the Object of
ObjectOrientedProgramming.
Cprogrammershadthousandsoflinesinheaderfileswhichcontainedtextlikethis:
#define DEFAULT_ACCOUNT 01123445
#define MAX_DRAW_NO 57

BorlandCprogrammershadthousandsoflinesscatteredaboutinthereheaderfiles
whichcontainedtextlikethis:
const char *DEFAULT_ACCOUNT = 01123445;
const int MAX_DRAW_NO = 57;

ThefirstcourseofactionwasactuallyANSIstandardC. Theprecompilerwould

Chapter1Fundamentals

61

textuallyreplaceeveryoccurrenceofthedefinedtextwiththesubstitutetext.Ifyouhad
asinglepasscompiler,thatwasasfarasitwent.Youwouldhavehowevermanycopies
ofthesevaluesaswasfoundduringthefirstpass.IfyouhadanNpasscompilerand
linker,eachinstanceoftheconstantsrequiringmorethanfourbytesofstorage(referto
typeandsizetableearlierinthisbook)wouldbereplacedwithapointerorreferenceto
asingleinstanceofthatconstantplacedinareadonlyconstantsPSECT.
Borland,neveronetofollowrules,decidedtointroduceconstantfoldingearlyon
intheClanguage,longbeforeitcouldevenbeconsideredforstandardization. Most
compilersflaggeditasanerrortohavethesameconstantdefinedmorethanonce,even
ifalldefinitionshadthesamevalue. Puttingtheconstdeclarationsinheaderfiles
would cause this to happen with every module that included them. The Borland
compilerwouldsimplyfoldalloftheseconstantsintoasingleinstanceoffinaread
onlyconstantPSECTwhichwasillegalaccordingtothestandardofthetimeandcaused
seriouslyheateddebate,especiallywhentheconstantsweredifferentvalues.
I'mbringingallofthisupbecauseOOPtossedarealmonkeywrenchintothings
whentheyallowedconstantstobedeclaredinobjectmethodsinsteadofrequiringthem
tobedeclaredasastaticconstantatthegloballeveloftheobject.

62

Chapter1Fundamentals

hello_class_const.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

//

The most familiar test program in the world.

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
class my_class {
private: int no_1, no_2, no_3;
char draw_dt[9];
public: void set_values( int a, int b, int c, char *d) {
const int MAX_DRAW_NO = 57;
if ( a <= MAX_DRAW_NO)
no_1 = a;
else
cout << "Invalid no_1 value" << endl;
if ( b <= MAX_DRAW_NO)
no_2 = b;
else
cout << "Invalid no_2 value" << endl;
if ( c <= MAX_DRAW_NO)
no_3 = c;
else
cout << "Invalid no_3 value" << endl;
strncpy( draw_dt, d, 8);
};
};
int main()
{
my_class m;
printf( "Hello Word!!\n");
m.set_values( 1, 59, 8, "20110425");
return 0;
}

WhenIwasgettingmydegreeincomputerscience,everystudenthadtotakeaclass
called something like compiler theory or compiler construction or theory of
compiler construction where we learned about Reverse Polish Notation, studied 2's
complimentyetagain,andlearnedthatyouputallconstantsinawriteprotected(read

Chapter1Fundamentals

63

only)PSECT. Nobodywhoactuallypassedacompilerconstructionclasswouldhave
allowedthisintothelanguagespecification.
Takeagoodlookatthetwohighlightedlines.WhileitistruethatIdidn'taddthe
inlinequalifiertothemethod,itisshortenoughthatitwillbeinlined.Nowlookat
listingline34andtellmewheremyobjectexists.That'sright,it'sontheSTACK,not
on the memory heap. While it is true that the object instance could actually be
constructed with a pointer to the member method, putting the member method
somewhereinanexecutablePSECT,asinglepasscompilationwouldnotdothis. In
theory,dependinguponhowthecompilerdancedaroundthisdebacle,wehavecompiled
executablecodeintotheprogramcallstack.Mostsecurityprofessionalswouldcallthat
anearmarkortrademarkofavirus. Theprogramcallstackissupposedtohaveonly
returnaddresses,returnvalues,parameters,andlocallydeclareddata. Likeeveryone
else,Iusedtosaylocallydeclaredvariables,butnowIsaydatabecausetheword
variablesisexactlyhowwegotintothissituation.
roland@linux-c345:~> g++ hello_class_const.cxx -o hello_class_const
hello_class_const.cxx: In function int main():
hello_class_const.cxx:38:39: warning: deprecated conversion from string constant
to char*
roland@linux-c345:~> ./hello_class_const
Hello Word!!
Invalid no_2 value

Let'slookataslightlydifferentversionofthisexample.

64

Chapter1Fundamentals

hello_class_struct2.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

//

The most familiar test program in the world.

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
class my_class {
private: int no_1, no_2, no_3;
char draw_dt[9];
static const char *DEFAULT_DATE;
public: void set_values( int a, int b, int c, char *d) {
const int MAX_DRAW_NO = 57;
if ( a <= MAX_DRAW_NO)
no_1 = a;
else
cout << "Invalid no_1 value" << endl;
if ( b <= MAX_DRAW_NO)
no_2 = b;
else
cout << "Invalid no_2 value" << endl;
if ( c <= MAX_DRAW_NO)
no_3 = c;
else
cout << "Invalid no_3 value" << endl;
strncpy( draw_dt, d, 8);
};
void display_values() {
cout << "no_1: " << no_1;
cout << " no_2: " << no_2;
cout << " no_3: " << no_3;
char *str = (char *)DEFAULT_DATE;
strcpy(str,"Fred");
cout << " draw_dt: " << draw_dt;
cout << " DEFAULT_DATE: " << DEFAULT_DATE;
cout << endl;
};
};
const char* my_class::DEFAULT_DATE

= "20110428";

int main()
{
my_class m;
printf( "Hello Word!!\n");
m.set_values( 1, 53, 8, "20110425");

Chapter1Fundamentals
51
52
53
54
55 }

65

cout << "displaying values now " << endl;


m.display_values();
return 0;

roland@linux-c345:~> g++ hello_class_const2.cxx -o hello_class_const2


hello_class_const2.cxx: In function int main():
hello_class_const2.cxx:50:39: warning: deprecated conversion from string constant
to char*
roland@linux-c345:~> ./hello_class_const2
Hello Word!!
displaying values now
Segmentation fault

I'mdiscussingthisexamplebecauseitwasnotallthatlongagowhenthisexample
wouldworkonseeminglyanyplatform. Manyplatformswillallowausertoelevate
theirprivenoughtomakeitworkeventoday,ifyoudon'tbelieveme,justthinkabout
howitisthePSECTgetsloadedthefirsttime.
Listingline33iswherewecastawaythe constnessofDEFAULT_DATE. This
eliminatesthecompilationwarningandallowsustocreateanexectable. OpenSuSE
apparentlymanagestosetprotectioncorrectlyonclasslevelconstants.Now,let'stweak
thiscodejustabitmore.

66

Chapter1Fundamentals

hello_class_struct2.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

//

The most familiar test program in the world.

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
class my_class {
private: int no_1, no_2, no_3;
char draw_dt[9];
static const char *DEFAULT_DATE;
public: void set_values( int a, int b, int c, char *d) {
const int MAX_DRAW_NO = 57;
if ( a <= MAX_DRAW_NO)
no_1 = a;
else
cout << "Invalid no_1 value" << endl;
if ( b <= MAX_DRAW_NO)
no_2 = b;
else
cout << "Invalid no_2 value" << endl;
if ( c <= MAX_DRAW_NO)
no_3 = c;
else
cout << "Invalid no_3 value" << endl;
strncpy( draw_dt, d, 8);
};
void display_values() {
const int MAX_DRAW_NO = 42;
cout << "no_1: " << no_1;
cout << " no_2: " << no_2;
cout << " no_3: " << no_3;
char *str = (char *)DEFAULT_DATE;
//strcpy(str,"Fred");
cout << " draw_dt: " << draw_dt;
cout << " DEFAULT_DATE: " << DEFAULT_DATE;
int *my_int = (int *)&MAX_DRAW_NO;
*my_int = 12;
cout << " MAX_DRAW_NO: " << MAX_DRAW_NO;
cout << my_int: << *my_int;
cout << endl;
};
};
const char* my_class::DEFAULT_DATE
int main()
{

= "20110428";

Chapter1Fundamentals
51
52
53
54
55
56
57
58
59
60 }

67

my_class m;
printf( "Hello Word!!\n");
m.set_values( 1, 53, 8, "20110425");
cout << "displaying values now " << endl;
m.display_values();
return 0;

roland@linux-c345:~> g++ hello_class_const2.cxx -o hello_class_const2


hello_class_const2.cxx: In function int main():
hello_class_const2.cxx:55:39: warning: deprecated conversion from string constant
to char*
roland@linux-c345:~> ./hello_class_const2
Hello Word!!
displaying values now
no_1: 1 no_2: 53 no_3: 8 draw_dt: 20110425 DEFAULT_DATE: 20110428 MAX_DRAW_NO:
42 my_int: 12

This isafinekettle offish. Most ofyouwill either beburned bythis orhave


alreadybeenburnedbythis.Whatactuallyhappensandwhatisallowedinthestandard
seemtovarywidely.Thestandardsaysthebehaviorisundefined.Manyplatformswill
let you modify the const, and many will not. Worse yet is what we see the GNU
compilerdoing.Itappearstopointthepointertosomeotherlocation,andallowsyouto
writethere.Thus,whenwecheckmy_int,weseethevaluewewant,butwhenwecheck
MAX_DRAW_NOweseetheoriginalconstantvalue.Iwillleaveitasanexercisefor
thereadertofindoutifwegetthesameaddressreturnedforallintegerconstants,ora
different address returned each time we attempt to take the address of an integer
constant.
C#/MonoandC++sharemanyofthesamerulesandcharacteristicsofstructures.A
structisasealedentity,unlikeaclass.Astructcannotbederivedfromanotherstruct.
Thatsaid,allbetsareoffwhenitcomestowhatgetsplacedinsideofastruct.Notonly
canastructcontaincodeandvaluetypes,but,inmaycasesyoucanputaclassinsideof
astruct.Thatclasscanevencontainmembervariableswhichhappentohavethesame
nameasmembersofthestruct.

68

Chapter1Fundamentals

hello_struct_class.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

//

The most familiar test program in the world.

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
class my_class {
private: int no_1, no_2, no_3;
char draw_dt[9];
static const char *DEFAULT_DATE;
public: void set_values( int a, int b, int c, char *d) {
const int MAX_DRAW_NO = 57;
if ( a <= MAX_DRAW_NO)
no_1 = a;
else
cout << "Invalid no_1 value" << endl;
if ( b <= MAX_DRAW_NO)
no_2 = b;
else
cout << "Invalid no_2 value" << endl;
if ( c <= MAX_DRAW_NO)
no_3 = c;
else
cout << "Invalid no_3 value" << endl;
strncpy( draw_dt, d, 8);
};
void display_values() {
const int MAX_DRAW_NO = 42;
cout << "no_1: " << no_1;
cout << " no_2: " << no_2;
cout << " no_3: " << no_3;
char *str = (char *)DEFAULT_DATE;
//strcpy(str,"Fred");
cout << " draw_dt: " << draw_dt;
cout << " DEFAULT_DATE: " << DEFAULT_DATE;
int *my_int = (int *)&MAX_DRAW_NO;
*my_int = 12;
cout << " MAX_DRAW_NO: " << MAX_DRAW_NO;
cout << " my_int: " << *my_int;
cout << endl;
};
};
const char* my_class::DEFAULT_DATE
struct my_struct {

= "20110428";

Chapter1Fundamentals
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

69

class my_class m1;


int my_int;
};
int main()
{
struct my_struct ms1;
printf( "Hello Word!!\n");
ms1.m1.set_values( 1, 53, 8, "20110425");
ms1.my_int = 255;
cout << "displaying values now " << " my_int: " << ms1.my_int << endl;
ms1.m1.display_values();
return 0;
}

roland@linux-c345:~> g++ hello_struct_class.cxx -o hello_struct_class


hello_struct_class.cxx: In function int main():
hello_struct_class.cxx:61:44: warning: deprecated conversion from string constant
to char*
roland@linux-c345:~> ./hello_struct_class
Hello Word!!
displaying values now my_int: 255
no_1: 1 no_2: 53 no_3: 8 draw_dt: 20110425 DEFAULT_DATE: 20110428 MAX_DRAW_NO: 42
my_int: 12

Toanyonewhodidn'thavethesourcecodetolookat,thisoutputwouldbeamajor
boottothehead.Noticethatthestructalwaysdefaultstopublicaccessbecausethat's
whatitwasoriginallyinC.Thatsaid,unlessyouknowwithabsolutecertaintythatyour
structcontainsonlyordinaryvaluetypesinit,Iwouldrefrainfromdoingabinarywrite
ofittoanyfile.Rememberalloftheearlierdiscussionaboutalignment?Thatreality
hasn'tgoneaway.Actually,itisoneofthemanyreasonsC++andOOPingeneralhad
tocomeupwithSerializableandSerialize.
Objectsmaybeniceinsideofyourprogram,but,youcannotensuretheexactsame
objectwillhavetheexactsamesizeandalignmentonanotherplatformoreventhenext
timeitisrun.MostOOPlanguagesprovideamethodforassigningauniqueversion
totheuniqueRTTI(RunTimeTypeIdentifier)andincludingatleasttheversionifnot
theentireRTTIvaluewhengeneratingtheserializedoutputofaclass.

70

Chapter1Fundamentals

IfI'mconfusingyou,don'tworry.Youreallyonlyhavetoknowthatthisdebacle
existedforclasses.TherearemanyexamplesforbothC#andC++online.OneforC#
canbefoundhere:
http://www.switchonthecode.com/tutorials/csharptutorialserializeobjectstoafile
Neverunderanyconditionsgettalkedintodoingthisforaproject!
Thereisabsolutelynoreasontoundergoserializationofobjectsinthisdayandage.
WehavedozensofOpenSourcedatabasessystemswhichareallfreeandoffervarious
levelsoffunctionality.ThereareevenJava,C++,andMonoclasslibrarieswhichwill
allowyoutoreadandwriteXBASEtypeDBFfiles.Formostdeveloperstodaythough,
SQLite, with its bind in capabilities will win out the day unless they are writing a
businessclassapplicationwhichrequiresabusinessclassdatabaselikePostgreSQL.
IfyoueverinterviewforajobprogramminginC++,Java,Mono,oranyotherOOP
languageandtheyaskyouifyouunderstandobjectserialization,simplygetupandwalk
outwithoutanswering.Shopslikethesestillexistandtheyshouldn't.Whatisthepoint
ofserialization?Tostoreinformationforfutureuse.Whatisthepurposeofadatabase?
To store information for future use. When the information is in a database, other
applicationswritteninotherlanguagescanaccessit.Wheninformationisserializedtoa
file,youhavetoloaditbackintoacompatibleobject.Asyoucansee,shopsstilldoing
serializationareindesperateneedofaqualifiedSystemsArchitect.

71

Chapter1Fundamentals
1.4 FriendsandProtection

Ifyouthoughtthepreviousdiscussiononstructures,classesandtheconstantswithin
wasaneyeglazer,youarereallygoingtolovethissection. Webrushedthetopicof
protection(alsoknownasaccessmodifiers)lastsection. Thissectionwillattemptto
explainthembetteranddiscussadebacleknownasfriends.
C++ tried to set the standard for access, and tried to keep it simple. Until the
creatorsofQtcameupwiththeconceptofSignalsandSlots,C++protection failed
miserably.
C++Access

Public

Protected

Private

Memberofsameclass

MemberofDerivedclass

World

Friendfunction

Friendclass

Ifnoprotectionwaslistedforaclassmemberormethod,andnoprotectionhadbeen
specified earlier in the class definition, the default protection level is private. It
shouldn'tbedifficulttoimaginethatthingsgotoutofhandwithmanyoftheC++class
libraries. Everythingwaseitherfriendorpublicbecauseyouneededtogetaccessto
thingstheoriginaldeveloperskeptlockedaway.
LetmeclearuponemajorpointofC++confusionhere:
class my_class : public some_other_class {}

Theabovestatementdoesnotcauseonlythepublicitemstobeinherited,allitems
willbeinherited.Whatthisdoesissettheminimumprotectionleveltobeappliedto
thoseinheritedthings.Ifwehadchosentosayprotectedinsteadofpublicallofthe
publicmembersandmethodswouldbeinheritedasprivateinmy_class. Allequalor

72

Chapter1Fundamentals

higherprotectionlevelswouldremainthesame.
C++isamajorsticklerfornotallowingthedowngradingofprotection.Ifamethod
isdeclaredprivate,youcannotderiveanewclassandoverridethatmethodwithapublic
version.
Java,developedsomeyearsafterC++hitthemarket,hadthebenefitofbeingableto
seewhatdidn'tworkinC++andtriedtofixsuchthingsintheJavaspecification.Java
added an access type and dropped friend. Java also tried to eliminate multiple
inheritance. Indeed, it removed the direct ability, then had to add Interfaces to the
language and allow for multiple Interfaces because single level inheritance couldn't
solvemostoftheproblemsdevelopersneededtosolve.

JavaAccess

Default

Public

Protected

Private

nomodifier
packageprivate
Member of same
class

Member of same
package

Member of derived
classinsamepackage

Member of derived
class in different
package

World

Chapter1Fundamentals

73

I'msureyounoticedthatlovelylittle*inthetable. Iwishitweren'tso,but,we
havetodelveabitdeeperatthispoint.ThedefinitiongeneratedbyyourJVMforyour
newclasswillcontainalloftheprotectedelementsandmethodsfromthebaseclass,
however,youcannotaccessthedataofaninstanceofabaseclassusingyournewclass
definition.
JavagotridofpointersbecausetheprogrammersworkingontheJavaspecification
could never make pointers work. It sounds cruel, but it is pretty much the truth.
Pointers got abused in C, I don't think the English language contains a word which
accurately describes whathappened tothem inC++. Itwas notuncommon tohave
classeswithmanylevelsofinheritancefromsomeBaseObject. SinceC++supported
quiet promotion/demotion as long as the classes had common ancestors, really bad
thingswouldhappen.

Illustration3:GenericClassHierarchy

Ialwaysloathcreatinginheritancediagrams. Nomatterhowyoudoit,someone
always wants the arrow heads pointing the other direction or the boxes organized
differently. For the sake of this discussion, inherited from both BaseObject and
OtherBaseObject.DerivedCinheritedfromDerivedB.

74

Chapter1Fundamentals

You can list a method/function parameter as DerivedC *c_ptr or BaseObject


*bo_ptr and receive one or the other, usually without any complaints from the
compiler. As long as the method/function receiving the pointer really only needed
thingswhichexistedintheBaseObjectclass,lifewasgood.IfyoucastaBaseObjectto
aDerivedCobjectinamethod/functionwhichreallyneededtheDerivedCcapabilities,
lifewasnotsogoodforyou.
Whatthelittle*inthetableistryingtoindicateisthatJavadoesn'tsupportthis
oftabusedC++capability,mainlybecauseiteliminatedpointers.
Microsoft,initsdesperateattempttoputanewcoatofpaintonitsJavaproduct,
changedthenamesofthings. Tostartwith,packagebecameassembly. C#removed
multipleinheritanceandfriendclasses,butkeptpointers.
C#/Mono

Public

ProtectedInternal

Internal

Protected Private

Memberof
sameclass

Memberof
sameassembly

Memberof
derivedclass
insame
assembly

Memberof
derivedclass
indifferent
assembly

World

Access

Chapter1Fundamentals

75

C#hasaweebitofanoddity.Thedefaultprotectionforthingsdeclaredinsideof
aclassorastructisprivate.Thedefaultprotectionforthingsdeclaredoutsideofaclass
or struct, but within a namespace is internal. Interface members and Enumeration
membersimplicitlyhavepublicaccessanddonotallowmodifiers.
ProtectedInternalisreadasprotectedorinternalnotwithanandjoiningthem
asmostwouldthink.
Most people say default access for C# is the most restricted access you could
declareforthatmember. Theoperativewordiscould. Ifyoudeclareyourclass
public,youcannotdeclareyoursettermethodsprivate.Ifyouareinheritingfromaclass
whichdeclaresamethodpublic,youcannotoverridethatmethodasprivateinyournew
class.Wewilldiscussthisabitmorewhencomparingnamespacesvs.packages.

1.5 Packages,Assemblies,andJNI
Yes,wearegoingtoveeroffintopackagesandassembliesatthispoint,notbecause
theyshouldcomenext,butbecauseIwanttocreatesomecodetoverifythatC#/Mono
access table we created in the previous section. You will find a lot of information
scatteredabouttheInternetofferingupconflictingwordingonthevariousaccesslevels.
IamguessingthevastmajorityofproductionC#codeusesProtectedInternaljustto
keepfromgoinginsane.
Packages end up being bundled into JAR files when working with Java. An
AssemblyisMicrosoft'sshinynewnameforanythingbuiltwiththemcscommand.
ThiscouldbeaDLLorexecutable.IntermsofMonotheDLLisreplacedbyashared
library. Icoveredtheinsandoutsofpackagesin TheMinimumYouNeedtoKnow
AboutJavaandxBaseJ ISBN13:9790982358030and TheMinimumYouNeedto
KnowAboutJavaonOpenVMSVolume1ISBN:0977086615soIamnotgoingto
wastepapercoveringthattopicyetagain.Findoneofthesebooksandreadit.

76

Chapter1Fundamentals

OnethingwewillmentionyetagainisJNI.TheJava Native Interfaceisasetof


toolsandspecificationswhichmakesyourClanguagefunctionscallablebyJavaclasses.
It is a rough specification and we worked with it almost exclusively in the Java on
OpenVMSbook.TheJNIisrequiredbecauseyourCmoduleswillbeexecutinginside
of a process, yet outside of the protected virtual machine environment. The Java
community deliberately makes it quite a burden to gain access to outside routines
becauseitwantsallcommonsystemservicestobeprovidedbytheVMandfound
somewhere in the System.blah.blah package tree. The problem is that highend
operating systems are so vastly ahead of feeble platforms like Windows, Unix, and
Linuxthatthecommonsetofsystemservicescan'tevenknockonthedoorofwhatis
availablenativelyontheplatform.Hence,Javadevelopmentonhighendplatformsis
alwaysasignificantpain.
I'mtalkingabouttheJNIfirstbecausethisisoneoftheplaceswhereMicrosoftwas
lookingtomoretightlycoupleJavatotheirworthlessWindowsplatform.C#/Monodid
notaddaJNI(C#NI)layer.Theychosetoprovidesomeautomaticallygeneratedcode
and link directly to the platformspecific library file. This my friends, is where
portabilitytookabigstinkydumpandawholelotoflawyersgotinvolved.
Thereweremanyargumentstossedabout.TheJavacommunitywastossingabout
theslogan Write Once,RunAnywhere andquietly ignoringanythinghavingtodo
withJNI.MostofthebookscoveringtheJNIhavelongsincebeenremovedfromthe
marketplace,withtheexceptionofmyJavaonOpenVMSbook.Nomatterwhatyoudo
withtheJNI,ifyouwantotherstobeabletouseit,somekindofinstalledorshareable
imagehastobecreatedandinstalledinamannerwhichmakesitaccessibletotheJVM.
WhatMicrosoftwasattemptingtodowasmaketheentireWINAPIavailabletoWeb
sites,thustightlycouplingthosesitestoMicrosoftdesktops.Whenthelawyersgotdone
and the dust started to settle, Microsoft was pretty much tossed out of the Java
communityand.NET(pronouncedDOTNOTbymostindustryinsiderseventhough
Microsoft'smarketingdepartmentpronouncesitDOTNET)startedtoemerge.

Chapter1Fundamentals

77

Duringtheintroductionchapter,yousawthefollowing:
roland@linux-c345:~/mega_Mono> mcs helloworld.cs
roland@linux-c345:~/mega_Mono> Mono helloworld.exe
Hello World!
roland@linux-c345:~/mega_Mono>

Theoutputofthemcscommandisactuallycalledasinglefileassembly.Thereare
alotofcompilationoptionsforthiscommandline.Therearealsomultiplecommands.
mcsuses1.0specificationwithpartsof2.0and3.0
gmcsuses2.0and3.0
smcsusesSilverlight/Moonlighttocreateapplicationsforuseinabrowser.
Whenaddingmultiplemodulestoalibraryyourcommandlinewouldlookmuch
likethefollowing:
mcs -t:library -o my_lib module1.cs module2.cs module3.cs

StandardUnix/Linuxlineshellscriptlinecontinuationruleswouldapply. SinceI
donotknowwhatshellyouarerunning,Icannotprovideadefinitiveanswer. When
compilingyourCmodulesyouwillneedtoincludethefPICcompileroptiononthe
command line. This tells the compiler to do the extra work of generating position
independentcode.Thistypeofcodecannotbegeneratedonallprocessors.Assuming
you get all of your C modules to compile cleanly using gcc, you will then issue a
commandlinelookingmuchlikethefollowing:
gcc -combine -shared -Wl,-soname,libmylib.so.1 -o libmylib.sl.1.o.1 \
module1.o module2.o module3.o module4.o

78

Chapter1Fundamentals

Thecombineoptionsayswewantitallinasingleoutputfile.Thesharedoption
indicateswearecreatingasharedlibrary.TheoddlookingcombinationofuppercaseW
followedbyalowercaselfollowedbysoname,libmylib.so.1actuallyallgoestogether
andcannothaveanyinterveningspaces.Thefirsttellsgcctopassthenextoptiontothe
linker. Thecommafollowingthatoptiontellsgcctocontinuepassingthenextlinker
option.Asonameisafieldofdatainasharedobjectfile.Itcontainsalogicalname
stringwhichdescribesthefunctionalityoftheobject.AllLinuxsharedobjectlibraries
muststartwith libandendwitha.sojustinfrontofthelibraryversion.Theversion
informationisactuallykeptinthefilename. Youonlychangethesonamewhenyou
significantlychangethelibraryinsuchawaythatitisnolongerbackwardlycompatible.
If youhave ashared object library and are indoubt as tohow far itis backwardly
compatible,youcanusethefollowingcommand:
objdump libname.so.1.3.4 -p | grep SONAME

Asalwayswithgcc,theooptionnamesouractualoutputfile.Iusedthebashline
continuationtostickalloftheobjectmodulesonthenextline.
bld_testaccess.sh
1
2
3
4
5

mcs -t:library -out:mylib1.dll mybase.cs deriv1.cs same1.cs


mcs -t:library -out:mylib2.dll -reference:mylib1.dll deriv2.cs
mcs -out:testaccess1.exe -reference:mylib1.dll,mylib2.dll testaccess1.cs

I'mnotexactlycertainifitwasduetosomerecentupdatesorthefactwenowhave
moreswitchesonthemcscommandline,butocausedcomplaintsthatIshoulduseout:
instead.I'mreallynotcrazyabouttheDLLandEXEextensionseither,but,thisiswhat
Microsoft wants. Notice how you need to specify the libraries you will use on the
compilationline?ThisisbecauseC#doesnothaveheaderfiles.WhencodinginC++
youwouldhavesimplyincludedalloftheheaderfileswithalloftheprototypesandthe
linkerwouldhavebeenleftwiththechoreoffindingthecorrectlibrary.

Chapter1Fundamentals

79

mybase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

using System;
namespace MyBase
{
public class MyBaseClass
{
public void the_public_method()
{
Console.Out.WriteLine("You Accessed MyBaseClass public method");
}
protected internal void the_protected_internal_method()
{
Console.Out.WriteLine(
"You Accessed MyBaseClass protected internal method");
}
internal void the_internal_method()
{
Console.Out.WriteLine("You Accessed the internal method");
}
protected void the_protected_method()
{
Console.Out.WriteLine("You Accessed the protected method");
}
private void the_private_method()
{
Console.Out.WriteLine("Hello World!");
}
}
}

Thisstuffisprettyselfexplanatory.Icreatedonemethodforeachtypeofaccess
protection.Whenitisinvokeditspitsalineouttotheconsole.

80

Chapter1Fundamentals

deriv1.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

using System;
using MyBase;
//
// First derived class will be compiled into same library
// We can call everything but private
//
namespace Deriv1
{
public class MyDerivedClass : MyBaseClass
{
public void test_access()
{
Console.Out.WriteLine("Testing Derived class in same assembly");
the_public_method();
the_protected_internal_method();
the_internal_method();
the_protected_method();
Console.Out.WriteLine(" ");
}
}
}

same1.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

using System;
using MyBase;
//
// This class just happens to be in same assembly
// We can call eveyrthing but protected and private
//
namespace Same1
{
public class Same1Class
{
public void test_access()
{
MyBaseClass mb = new MyBaseClass();
Console.Out.WriteLine(
"Testing class in same assembly but not derived");
mb.the_public_method();
mb.the_protected_internal_method();
mb.the_internal_method();
Console.Out.WriteLine(" ");
}
}
}

Chapter1Fundamentals
deriv2.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

using System;
using MyBase;
//
// Second derived class will be compiled into different library
// We can call everything but internal and private
//
namespace Deriv2
{
public class MySecondDerivedClass : MyBaseClass
{
public void test_access()
{
Console.Out.WriteLine("Testing Derived class in different
assembly");
the_public_method();
the_protected_internal_method();
the_protected_method();
Console.Out.WriteLine(" ");
}
}
}

81

82

Chapter1Fundamentals

testaccess1.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

using
using
using
using
using

System;
MyBase;
Deriv1;
Same1;
Deriv2;

namespace TestAccess1
{
class TestAccess1
{
static void Main(string[] args)
{
MyBaseClass mb = new MyBaseClass();
// From outside world we can only access public
//
Console.Out.WriteLine(
"Testing World access outside of assembly");
mb.the_public_method();
Console.Out.WriteLine(" ");
MyDerivedClass md = new MyDerivedClass();
md.test_access();
Console.Out.WriteLine(" ");
Same1Class s1 = new Same1Class();
s1.test_access();
Console.Out.WriteLine(" ");
MySecondDerivedClass md2 = new MySecondDerivedClass();
md2.test_access();
}
}
}

Eachderivedclasstestsbysimplytryingtoaccessthemethods.Thesame1classand
thisclassmustdeclareinstancesoftheobjectinordertotest.PleasenotethatC#/Mono
doesnotletyoudeclareanobjectonthestacklikeC++did.Listingline13declaresa
reference namedmbtoanobjectofMyBaseClasstype. Untilwecallnewtoactually
createaninstanceofthatobjectthereferenceiseithernullorundefined. Remember,
C#/MonoismostlywhitewashedJava.IfyoureadTheMinimumYouNeedtoKnow
AboutJavaonOpenVMSVolume1youwillfindaniceexplanationofthisinstance
andreferencestuffinthesectiontitledEverythingisaClass(almost).

Chapter1Fundamentals

83

SinceIputtheactualtestingcodeineachoftheclasses,weonlyneededtocreate
theworldaccesstestinginthisclass.
roland@linux-c345:~/mega_Mono> Mono ./testaccess1.exe
Testing World access outside of assembly
You Accessed MyBaseClass public method
Testing Derived class in same assembly
You Accessed MyBaseClass public method
You Accessed MyBaseClass protected internal method
You Accessed the internal method
You Accessed the protected method
Testing class in same assembly but not derived
You Accessed MyBaseClass public method
You Accessed MyBaseClass protected internal method
You Accessed the internal method
Testing Derived class in different assembly
You Accessed MyBaseClass public method
You Accessed MyBaseClass protected internal method
You Accessed the protected method

1.6 ProgrammingAssignment1
Youdidn'treallythinkIwasgoingtogettopage100inthisbookwithoutstartingto
handoutprogrammingassignmentsdidyou?Yourassignmentistomodifythiscodeto
testeachoftheaccessmethodswhicharenotallowedaccordingtothechart.Yes,you
willhavetoeditandcompilemanytimesbecausethereisnowayforyoutocomplete
thisassignmentonasinglepass.

1.7 ProgrammingAssignment2
ItshouldcomeasnosurprisetoyouthatC#hasthesamethispointerasC++.
Youaretoaddprivatedataelementstothebaseclass,thenaddmethodstoeachofthe
thederivedtestclasseswhereyoucastthethispointertothebaseclassandattemptto
accessbothprivatemethodsandprivateelements.

84

Chapter1Fundamentals

1.8 NativeCodeContinued
Webrushedonthetopicsofnativeaccessandunmanagedcodesection1.5,butI
neededtoshowyouhowtobuildMonolibrariesbeforewecontinuedonwithaccessing
native libraries. Some things are similar and some things are different from our
discussionaboutaccessMonoroutines/classesinDLLfiles.Tostartwith,Monoforks
off rather distinctly from C# when it comes to calling native code. C# expects
everything tobeinaDLLfileandisn't toopolite aboutanydeviation. C#willnot
automaticallyappendthe.DLLtothenameifyouaccidentallytypeaperiodattheend
ofyourfilename.
I'mgoingtobequitestraightforwardwiththissectionandtellyouthatmostJava
programmerspuntwhenitcomestowritingJNI.Iftheycannotpurchaseaclasswhich
already does what they need, they simply refuse to write the code. If you want to
understandwhyreadTheMinimumYouNeedtoKnowAboutJavaonOpenVMS.
AnyonewhohasreadtheMicrosoftpublicationsoncallingC/C++codefromC#
willbeabitconfusedwhenitcomestohowMonochosetodothings.Itwasn'tjustthe
Monocommunity,GNUhadalottodowithitaswell. OntheworthlessWindows
platform,youonlylinkDLLs. OntheworthlessWindowsplatformMicrosoftforces
youtousetheirVisualStudiofordevelopmentandthus,controlshoweverythinggets
donewithoutactuallyexposingmuchofit.
TheoriginalversionofthisexampledidallofthecalculationsinsideoftheCand
C++functions.IcouldnotgetittolinkcorrectlyonOpenSuSE.Theproblemisthat
GNUdidn'timplementthepow()functionlikeotherthings.Ifyouarecreatingastraight
CorC++programyoumustuselmonthecompilationlinetoinformthelinkerabout
pow().Ididnotfindamagicmethodofmakingthisworkwithmcs.Yes,I'msuremany
willvolunteersomekindofsolution,butIdidn'tfeellikediggingquitethatdeepinthe
manuals.Itiseitherrarelydoneorscoffedat,because,thereisnothingaboutitonline
otherthantheerrormessageyouget.

85

Chapter1Fundamentals
NativeClass.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

using System;
using System.run-time.InteropServices;

// gotta have this

public class NativeClass


{
[DllImport ("MyLib")]
private static extern double amort_1( double loan_amount,
double interest,
double compound_rate);
[DllImport ("MyLib")]
private static extern double balance_remaining( double loan_amount,
double interest,
double compound_rate,
double curr_compound);

public static void Main()


{
Console.Out.WriteLine("$350,000 for 60 months at 5.25%");
double monthly_interest = 0.0525/12.0;
double compound_rate = Math.Pow( (monthly_interest+1) , 60);
double monthly_payment = amort_1( 350000.00, monthly_interest,
compound_rate);
Console.Out.WriteLine(" Monthly Payment {0:C}", monthly_payment);
Console.Out.WriteLine("\n\n");
Console.Out.Write("Balance paid by payment 40: ");
double curr_compound = Math.Pow( (monthly_interest+1) , 40);
double balance = balance_remaining( 350000.00, monthly_interest,
compound_rate, curr_compound);
Console.Out.WriteLine("{0:C}",balance);
}

30
31
32
33 }

Our example program is going to call some existing mortgage formulas. I


intended this to be a quasireal world example. If there were any existing
heritage/legacy/preexistingfunctionsoutthereacompanywouldnotwanttorewriteor
invent,itwouldbefinancialstuff.IfIhadn'tbeenscrewedbyGNU'simplementationof
pow(),thisexamplewouldhavebeenperfect. Asthisexampleunfolded,Iendedup
havingtousethePow()methodprovidedbyMonotocalculateportionsoftheformulas
whichmakestheactualformulaslookweird.

86

Chapter1Fundamentals

fun_1.c
1
2
3
4
5
6
7
8
9
10
11
12
13

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double amort_1( double loan_amount, double interest, double compound_rate)
{
printf( "\nloan_amount $%9.2f
interest %7.6f
compound_rate %f\n\n",
loan_amount, interest, compound_rate);
return (loan_amount *
((interest * compound_rate ) / (compound_rate - 1 )));
}

Fromalanguageperspective,thereisnothinginterestinghere.Wegetawaywith
passing doubles because Mono relies on GNU; hence the types are the same. The
doubletypewillnotbethecasewithothercompilers,norwoulditbethecaseifother
switcheswereusedonthecompilationline.
fun_2.cpp
1
2
3
4
5
6
7
8

#include <math.h>
extern "C" double balance_remaining( double loan, double interest,
double compound_rate, double curr_compound)
{
return (loan * ( compound_rate - curr_compound)
/ ( compound_rate - 1));
}

NoticethatwehavetoforcetheClanguagecallingconventionwhenusingC++.
WithvariousDOS/Windows/andOS/2compilerswehad__cdeclkeywordswhichcould
beforcedintoaltercallingconventions.
http://en.wikipedia.org/wiki/X86_calling_conventions
http://www.openwatcom.org/index.php/Calling_Conventions

Chapter1Fundamentals

87

bld_native.sh
1
2
3
4
5
6
7
8
9

gcc -fPIC -c -o fun_1.o -Wall fun_1.c


gcc -fPIC -c -o fun_2.o fun_2.cpp
gcc -combine -shared -Wl,-soname,libmylib.so.1 -o libmylib.so.1.0.1 \
fun_1.o fun_2.o

mcs -out:NativeClass.exe -lib:/home/roland/mega_Mono NativeClass.cs

The fPIC compiler switch tells the compiler to always create relocatable code.
Whilethisisknowntobethedefaultonx86Linuxplatforms,it'snotalwaysthecase,
particularly if you include oddball calls like pow(). Quite simply Wall tells the
compilertodisplayallwarnings.
IfallyoudoisincludethehighlightedlibswitchwhencompilingyourMonocode
touseasharedobjectlibrary,don'tbesurprisedifyouseethefollowingerrormessage
ateithercompiletimeorruntime:
Mono error CS0006: cannot find metadata file ".so"

There is one file needed which I have yet to discuss. Please look back at the
DllImportlinehighlightedinourcsfile. Ichosenottodiscussitthenbecauseitisa
muchbiggerdiscussionthanitssizewouldindicate.Thisline,initscurrentstate,isalso
amassivelysignificantforkfromC#.Remember,Microsoftisonlyworriedaboutbeing
compatiblewithotherversionsofwhateverproductMicrosoftissellingasanoperating
system,butMonoislookingforcompatibilitywiththeworld.
MostpeopleareintelligentenoughtorealizethatMicrosoftisveryquicklyonits
waytojoiningSingerandWangasnamescoveredbydustinthefootnotesofcomputing
history. Some of these people are even the founders and/or early employees of
Microsoftwhoarenowspendinglotsoftheirowncasheitherquietlyorpubliclybacking
the development of Mono so Microsoft doesn't join that long list of once mighty
computinggiantsthatdisappearedwithoutactuallycontributinganythingmeaningfulto
the computing industry. There have been many names since the early 1970s which

88

Chapter1Fundamentals

came,generatedmillions,thendisappearedwithoutleavinganythinglastingbehind.
You will find that most Mono code ends up being nonportable because the
developer puts some platform specific name in the DllImport statement. This is a
horribly sad state of affairs and one which should not exist. The Mono runtime
automaticallylooksforprogname.exe.configinthesamedirectoryitfindstheexefile.
Thisconfigfileisprocessedpriortoyourprogram.Amongthemanythingsyoucando
insideoftheconfigisprovideplatformspecificnametranslation.
NativeClass.exe.config
1
2
3

<configuration>
<dllmap dll="MyLib" target="libmylib.so.1.0.1" />
</configuration>

Ifyouneedtoincludenativecodeforwhateverreason,youcansimplykeepa
different config file for each operating system and have your install (or distribution
packager)renamethecorrectfile. HerewemappedthegenericMyLibnametothe
platformspecificsharedobjectlibrary.
Buildingandrunningtheprogramyieldsthefollowing:
roland@linux-c345:~/mega_Mono> ./bld_native.sh
roland@linux-c345:~/mega_Mono> Mono NativeClass.exe
$350,000 for 60 months at 5.25%
loan_amount $350000.00

interest

0.004375

compound_rate

1.299432

Monthly Payment $6,645.09

Balance paid by payment 40:

$126,987.76

Admittedly,ifthisexamplehadbeenphysicallyreusingmethodswhichdidallof
thecalculationstheexamplewouldhavehadmorerealworldimplicationstoit.Oneof
thereasonsMicrosoftwantedtomakeitsosimpletolinkinnativecodewastotryand
extendtheusabilityofeverythingwhichwasalreadywritten.Oneofthebiggestpitfalls
ofexecuting native code ontheWeb isthatthebrowser which connected toyour
servicehasacompletelydifferentOSbehindit.

89

Chapter1Fundamentals
1.9 Arrays

You may wish to pour yourself a fresh beverage before reading this section.
Traditionally,arrayswerethebeginningofpointerdiscussionsindatastructuresclasses.
IfyouhappentohavebeentaughtdatastructureswhileyouwerebeingtaughtPASCAL,
then,youshouldfullyunderstandwhytheworldhatesPASCALandthosewhokeep
pushingit.
Wewerealltaughttoviewarraysmentallyaseitheracontiguousstack,oran
endless string. Your very first set of examples involved only integers, usually
longwords,andtheyseemedsosimple.
6

13

14

18

4
2
8
7

Nomatterhowyoumentallyviewedthearray,thechoiceofdatatypeshidsome
uglyalignmentfacts.Mostofyousattherehappilycodingarraynavigationbyusinga
pointerthatwasincrementedbyoneratherthanasubscript.Ifyouhadnotbeenforced
toenduretakinganAssemblylanguageclassatthispoint,youhadnoideawhathardship
awaitedyou.

90

Chapter1Fundamentals

ThosewhowereluckywentontotakeaC/C++programmingclass.Thereyougot
ahintaboutjusthowuglythingsreallywereunderthehood.Perhapsittookuntilafter
graduation,but,eventuallyyouaskedthequestionWhydoesChavebothmalloc()and
calloc()?IfyouspentanytimeatallasamaintenanceCprogrammer,youwitnessed
someGodawfulabusesofmalloc()toforcegettingacontiguousregionjustsosomeone
couldinefficientlymanipulateapointerratherthandereferenceasubscriptedvariable.
MBAsinthecomputingworldlovetomaketheexactsamemistakesaseveryother
MBA who hascome before them. Itappears that thekinds of engineers who these
MBAs talk with also like to commit the same mistakes. In the early days of the
mainframecomputer,designersdecidedthatmemorywassoexpensivethatnocompany
or government could ever afford more than X amount of it. Software was not an
industrythen,hardwarewas. Thehardwareengineersdidn'twanttolimittheaddress
space for their asofyetuninvented devices, so they picked a high base address for
hardware addon cards, thus creating the stage for a memoryhardwarememory
segmentationissue.
SkipafewyearsforwardandyouwillfindthedesignersoftheoriginalIBMPC
making the justification that the largest mainframe in production only had 640K of
RAM,sohowcouldatoycomputerneedmore?Notonlydidthisthinkinggiveusthe
magic640KboundaryyouhearaboutintheDOSworld,italsogaveusthattreacherous
384Kregionaboveitwhereadaptercardscouldbeaddressed,andmemorymanagers
attempted to load things high. In other words, we relived the
memoryhardwarememorysegmentationissuesagain.
Everycomputeroperatingsystemwhichallowsforpagingorswappingtodiskmust
insomewaydealwithmemorysegmentationbecauseyouneedtomeasuretheamount
ofmemorybeingmovedaround.Whatisinexcusableisthememoryholescreatedby
hardware designers. The combination of memory segmentation with memory holes
madearraysfarmorecomplexthantheyneededtobeinC/C++andotherlanguages.

Chapter1Fundamentals

91

WetouchedlightlyonthePCmemorymodelsysteminsection1.3.Eachsegment
underDOSwas64Kinsize.DOSdidnotdirectlysupportpagingand/orswappingto
disk.AnaddressunderDOSfitintoalongwordandwasoftheformsegment:offset.
EverymemorymodelexceptCompactusedthistypeofaddress. UndertheCompact
memorymodeleverythinghadtofitintoonesegment,soallpointerswereonlyaword
insizeandtheycontainedonlytheoffset.
I am sorry that I have to expose you to this level of discussion, but, without
understanding the vicious flaw created by the hardware geeks, you cannot begin to
understandjusthowdifficultarraysweretooriginallyimplement.Ofcourse,youhave
totakealookatsomeprettycommoncodetounderstandwhythiswas.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

char *line_in, *tmp;


line_in = malloc( 40000);
do
{
memset( line_in, '\0', sizeof( line_in));
fgets( line_in, sizeof( line_in) -1, in_file);
if ( !feof(in_file))
{
tmp = &line_in[0];
while (*tmp != '\0')
{
if (*tmp == 'A')
*tmp = 'b';
tmp++;
}
}
}

while (!feof(in_file));

OtherthanaperplexingquestionastowhyanybodywouldwanttoreplaceAwithb
inthismanner,thereisreallynothingwrongwiththiscode. Ihaven'tcompiledand
testedit,butwearen'tlookingforasyntaxerror.(Okay,Ididn'tcheckforthemalloc
failureanddidn'tfree,butthat'snotwhereweareheadedwiththisdiscussion.)There
wasnothinginmostcompilerandoperatingsystemenvironmentstostopmalloc()from
allocatingmemoryacrosssegmentboundaries.Itwasnotuncommontoseetheexact
sameexecutablefilerunperfectlyonmanydifferentDOSbasedcomputers,thenfail
miserablyonthenextinstallationbecausethatuserhaddifferentdriversorsomething

92

Chapter1Fundamentals

loadedwhichchangedthestartingaddressofthefreeheap.Thereweremanycompiler
bugsinvolvingfailuretoincrementthesegmentwhentheoffsetrolledover.
Hadtheabovecodebeenwrittentonotusepointermath,itwouldhaveworked
correctlyinallenvironments.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

char *line_in;
int x;
line_in = malloc( 40000);
do
{
memset( line_in, '\0', sizeof( line_in));
fgets( line_in, sizeof( line_in) -1, in_file);
if ( !feof(in_file))
{
x = 0;
while (line_in[x] != '\0')
{
if (line_in[x] == 'A')
line_in[x] = 'b';
x++;
}
}
}

while (!feof(in_file));

Thepushtousepointersinsteadofthissyntaxcamefrommanydirections.Firstoff,
manyofuswereusingdesktopcomputerswithawhopping4.77Mhzclockspeed.The
CPUinyourcurrentcellphonerunsringsaroundthoseoldchips.Wehadtosaveclock
cycleswhereverwecouldandnearlyeverygeekofthedaycouldquoteoffthetopof
theirheadjusthowmanyclockcycles*tmpsavedoverline_in[x].
C++hadtomaintainbackwardcompatibilitywithC,soallnativeornaturaldata
typeshadarrayscreatedastheywereinC,butallarraysofobjectswerecreatedusingan
Array class. Every C++ compiler and library vendor rushed to enhance the C++
languagefurtherbyprovidingtheirownStringclassestoeliminatethepreviouscoding
examples.EventuallyaStringclasswasmadepartoftheC++standard,completewith
iterator,compare,substring,find,andmanyothermethodstypes. Notonlycouldyou
addtoyourStringobject,youneverhadtoallocateitorknowitssize.Therewasno
longeranyrealisticpossibilityofwritingpasttheendofastringbuffer.

Chapter1Fundamentals

93

Javadidn'thavetosupportC,so,itremovedallnativememorymanagementand
forcedallarraystobeArrayobjects.Javaevenremovedthesyntaxwhichcouldconfuse
adeveloper.
HelloWorldArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

import java.util.Random;
import java.util.Arrays;
public class HelloWorldArray
{
public static void main(String[] args)
{
System.out.println( "Hello World!");
int [] ar1 = new int [] {11,6,2,46,9};
int ar2[];
ar2 = new int [6];
Random gen = new Random();
System.out.print( "Second array");
for (int x=0; x < ar2.length; x++)
{
ar2[x] = gen.nextInt();
System.out.print( " " + ar2[x]);
}
System.out.println( "\n\nSorted output");
System.out.print( "Array One: ");
Arrays.sort(ar1);
for (int k=0; k < ar1.length; k++)
System.out.print( " " + ar1[k]);
System.out.print( "\nArray Two: ");
Arrays.sort( ar2);
for (int j=0; j < ar2.length; j++)
System.out.print( " " + ar2[j]);
System.out.println( "");
}
}

Listinglines11and12showtheprimarymethodsofdeclaringarraysinJava.What
isimportanttonoteisthatifyouputanumberinthe[]asyouwouldinC,youwillgeta
syntaxerror.

94

Chapter1Fundamentals

Listingline17showshowweusethelengthmembervariableandlistingline25
showshowtousethesort()methodprovidedbytheArraysclass.Pleasenotethatthe
sort() method isn't part of the array you create. The Arrays class contains utility
methodsforcomparing,searching,andsortingnativedatatypearrays,it'snotactually
theclassyouderivefromwhencreatinganarray. Thisisthereasonwecouldnotdo
ar1.sort().
Iwillshowyoutheoutputnow,butwewon'tdiscussituntilwediscussournext
program.
roland@linux-c345:~/mega_Mono> javac HelloWorldArray.java
roland@linux-c345:~/mega_Mono> java HelloWorldArray
Hello World!
Second array -910660675 464638207 -841371297 -2115529447 -836877961 2101164408
Sorted output
Array One: 2 6 9 11 46
Array Two: -2115529447 -910660675 -841371297 -836877961 464638207 2101164408

Chapter1Fundamentals
helloworldarray.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

using System;
using System.Collections;
namespace HelloWorldArray
{
class Hello
{
static void Main(string[] args)
{
Console.Out.WriteLine("Hello World!");
int [] ar1 = new int [] {11,6,2,46,9};
int[] ar2;
int[] ar3 = {28, 34, 66, 77, 1, 6, 2};
ar2 = new int [6];
Random gen = new Random();
Console.Out.WriteLine("Second Array");
for (int x=0; x < ar2.Length; x++)
{
ar2[x] = gen.Next();
Console.Out.Write( " " + ar2[x]);
}
Console.Out.WriteLine( "\n\nSorted output");
Console.Out.Write( "Array One: ");
Array.Sort(ar1);
for (int k=0; k < ar1.Length; k++)
Console.Out.Write( " " + ar1[k]);
Console.Out.Write( "\nArray Two: ");
Array.Sort( ar2);
for (int j=0; j < ar2.Length; j++)
Console.Out.Write( " " + ar2[j]);
Console.Out.WriteLine( "");
Console.Out.Write( "\nArray Three: ");
Array.Sort( ar3);
for (int j=0; j < ar3.Length; j++)
Console.Out.Write( " " + ar3[j]);
Console.Out.WriteLine( "");
}
}
}

95

96

Chapter1Fundamentals

JustlookathowshockinglydifferentC#/MonoisfromJava!(coughcoughcough)
FirstweincludeSystem.Collectionsinsteadofjava.util.Arrays.Nextwefindthatyou
cannotputthe[]ontherightsideofavariablenametodeclareanarrayreference. I
addedthethirdarraytopointoutaninterestingtwistC#allowswhichcurrentlyisn'tpart
oftheJavaspecification.Noticehowitwillautomaticallycreatetheobjectstobestored
inthearraywithoutusexplicitlytellingitto.IbelievethistobeaconcessiontoC/C++
programmerswhohavebeenusedtotypingthingslike:
int x_array [] = {24, 66, 32, 55, 77, 11};

Ournexttwohighlightedlineshavelittletodowitharraysandmoretodowithjust
howdrasticallydifferentMicrosoftmadeC#fromJava.(coughprofuselyhere!)Instead
of the Java Arrays.sort() call we call the C#/Mono Array.Sort(). More importantly
Randomdoesn'thaveanextInt()methodlikeJava,ithasaNext()method.
I'm telling you,Microsoft sparednoeffortwhenitcametomakingC#different
fromJava!
One thing they did not bother building into C#/Mono arrays is the FORTRAN
abilitytostartatanybaseusinganystep.Whileyoumaynotunderstanditnow,when
youareorganizingstuffbyyearsanddidn'thavecontiguousyearsofinformation,that
wasagreattool.
Theoutputofoursampleprogramshouldn'treallyshockyou,orshouldit?
roland@linux-c345:~/mega_Mono> mcs helloworldarray.cs
roland@linux-c345:~/mega_Mono> Mono helloworldarray.exe
Hello World!
Second Array
1421218565 2116754422 905560231 1579982750 1635971461 1856576989
Sorted output
Array One: 2 6 9 11 46
Array Two: 905560231 1421218565 1579982750 1635971461 1856576989 2116754422
Array Three:

1 2 6 28 34 66 77

Chapter1Fundamentals

97

IfyoucomparethisoutputtotheJavaoutputitshouldbepainfullyawarethatwe
didn'tobtainanynegativenumbers. Javaonlyallowsyoutosetaseedvaluewhich
improves the distribution of random numbers, but, if you don't provide a maximum
valueonthenextInt()call,anyvalueinthe2^32rangecanbereturned.Ifyouprovidea
maximumvalue,therangewillbezeroandthevalueprovided.
C#,bycontracts,startswithabaseofzero.WhenyoucallNext()youcanpassa
maximumvaluebyitselftocapthereturn,buttheonlywaytogeta potentiallynegative
numberistopassbothaminimumandmaximumvaluetoNext().Whileyoumightnot
thinkmuchofthisnow,Icantellyoufromexperienceit'saprettymassivedifference.
Mostofyounevertestwithortrapfornegativenumbers.IadmireJavaforthrowing
thatmonkeywrenchintothemixearly.

1.10 ProgrammingAssignment3
YouaretowritebothJavaandMonoprogramstoprintout100randomnumbers
withoutusingaseedvalue. Runeachmultipletimesandcomparetheoutput. Does
either Java orMono always provide you the same predictable set of pseudorandom
numbers?

1.11 Enums
I'mnotabigfanofenums. Yes,Ibelieveenumshavetheirplace,buttheyare
poorlytaughtandevenmorepoorlydesigned. Theproblem isthatprogrammersare
taught by the white smocked wearing OOP crowd that an object should contain
everything.Studentsthenendupcreatingallofthesehalfarsedsystemsthathardcode
allaspectsofanobjectinenumsthenserializestuffouttoflatfiles.Studentsthenget
jobsintherealworldandgetPostTraumaticStressDisorderwhentheyaretoldthe
company issuingtheir checkwants all ofthedatainarelational database,notsome
serializedflatfileontheirlocalPC.
Hereistherule: UnlessyouarewritingagraphicslibrarylikeQtorZinc,never,
underanycircumstances,useanenum.

98

Chapter1Fundamentals

Enumshavebeenabusedanduniversitieshavebeenabsolutelywretchedwhenit
comes to teaching proper production quality software development. Other than
graphicaluserinterfaceprimitiveswhichwillneverbestoredinadatabase,thereisno
goodreasontouseanenuminproduction.
Let'stakeafamiliarexample,aPoloShirtinaclothingcatalogandwalkthroughthe
reasoning. The Polo Shirt has asingle base catalog item number assigned to it for
ordering.Thepersonplacingtheorderisthenaskedtochooseasizeandacoloralong
withanyMonogrammingtheywantdone.Whatreallyhappensinaproductionsystem
isthateachsizeandcoloroptiontranslateseitherdirectlyorindirectlyintothevalues
completingtheactualinventoryitemnumber.AnOOPprogrammerfreshoutofschool
willcreateaclassPoloShirtwhichcontainsenumsforcolorandsizealongwithan
internalconstantforthecatalogitemnumber.Inshort,theycreatesomethingworthless.
Theentireproductionsystem isgoingtorevolvearoundacentraldatabase. The
tablewhichisusedtogeneratethecatalog,eitheronlineorinprint,willcontainthe
catalogitemcode,ashortdescription(itemtitle),alongdescription,andtheneitheran
imageinablob,oraURLtoastockimage.Aninventorytablewillexistcontainingone
rowforeachUPCfromthevendor.EachUPCwillbetiedtoonecombinationofsize
andcolorforthatshirt.Ifyourvendorispolite,thefirstNdigitsoftheUPCwillbethe
sameforallitems,andthelastcoupledigitswillvarysequentially,butdon'tcountonit.
Because of this each row in UPC table will contain a repeating key column for
inventory_item or inventory_parent_item, depending upon how your system was
designed.Thecatalogtablewillalsocontainthisinventory_parent_itemvalue.
Itshouldbenotedherethatveryoldretail,andmostdirectmanufacturerdatabase
and system designs will be different. The last 10 years has seen a push for every
manufacturerintheworldtoassignauniqueUPCtoeachandeverypermutationoftheir
productline.Oldapparelorderingsystemsformanufacturersusedtosimplybreakup
itemsbymaterialandpassthesizealongasinformationtothepieceworkticketbecause
onlythecutterneededtoknowthesize.I'msuresomesystemslikethatstillexistand
maybeusedinternally,but,ifyouaresellingtoanyofthemajorretailers,youhave

Chapter1Fundamentals

99

someothersystemwhichinterfaceswiththemandusesauniqueUPCforeachpossible
combination.
Whyhasthispushhappened? ConsiderforamomenttheStaffordWrinkleFree
Executive men's suit shirt. While it comes in several colors and many size
combinations,whiteandbluetendtobethemostwidelysoldwithwhiteleadingbyfar.
(Notonlyistheshirtwornbymenwithsuits,but,manyrestaurantsmandateitorthe
Oxfordversionofitfortheirfemalewaitstaff.)WhenyourlocalJ.C.Penny'sstocksout
ofthewhite18neck36sleeveversionofthisshirt,theydon'twanttoplaceanorder
for more white Wrinkle Free Executive shirts and let the supplier guess at the size
becausethat'showyouendupwithastorefullof15necksand32sleevesnobodycan
fitinto.
Inventorymanagementhasmovedintothe21 st century. Whilemanyretailchains
stillhavepeoplewiththetitlebuyer,theyaregenerallyonlythebuyerofnewitems.
Thevastmajorityofinventoryreplenishmenthappenswithoutanyhumaninvolvement.
Whenthesalescannedatthecashregistersetsthecurrentinventorybelowthesafety
stockquantitythereorderwilleitheroccurinstantlyorwiththenightlyjobstream.
Sincewemustcoverenumstobecomplete,letusreturntotheirdiscussion.Unless
youforceastartingvalueforyourenum,itwillstartatzero.DuringthedaysofC/C++
enumsusedtoequate tointeger,theyarenowtheirowntypeandmustbecasttoa
numericdatatypeifyouwishtousethevalue.Thismayconfusesomepeoplebecause
underC#/Monoeachenummusthaveabasetype,whichbydefaultisint,butcanbe
anyintegraltype.Youcanchangetheintegraltypebyusinga:followedbythetype
asourexampleprogramshows.

100

Chapter1Fundamentals

helloworldenum.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

using System;
namespace HelloWorldEnum
{
class Hello
{
enum AutoIgnition :long
{GASOLINE=536, FUELOILNO2=494, ETHYLALCOHOL=689,
METHANOL=878,SULPHUR=470};
static void Main(string[] args)
{
Console.Out.WriteLine("Hello World!");
Console.Out.WriteLine("AutoIgnition values:");
Console.Out.WriteLine("GASOLINE = {0}",
(double)AutoIgnition.GASOLINE);
Console.Out.WriteLine("FUELOILNO2 = {0}",
(double)AutoIgnition.FUELOILNO2);
Console.Out.WriteLine("EHTYLALCOHOL = {0}",
(double)AutoIgnition.ETHYLALCOHOL);
Console.Out.WriteLine("METHANOL = {0}",
(double)AutoIgnition.METHANOL);
Console.Out.WriteLine("SULPHUR = {0}",
(double)AutoIgnition.SULPHUR);
}
}
}

roland@linux-c345:~/mega_Mono> mcs helloworldenum.cs


roland@linux-c345:~/mega_Mono> Mono helloworldenum.exe
Hello World!
AutoIgnition values:
GASOLINE = 536
FUELOILNO2 = 494
EHTYLALCOHOL = 689
METHANOL = 878
SULPHUR = 470

Yes,Iprovidedyouwiththesamekindofbadexampleyouwillfindalloverthe
Internet.Ratherthanputtingdatainadatabase,Iusedanenumtodeclareabunchof
constantvalues.NoticethatIusedalongdatatypeeventhoughallofthesevaluescould
haveeasilyfitintoaninteger. Youalsoneedtonotethatyoucannotuseanytypeof
floatingpointforanenum,itmustbesomevariantofanintegerdatatype.Pleasenote
thatyoucanconvertanintegerintoafloatingpointdatatypeasIdidatlistingline17.

Chapter1Fundamentals

101

Ifyoudonotprovideanyvalues,simplyalistofnames,thenameswillhavevalues
startingsequentiallywithzeroandincrementingbyone.Ichosetoassigneveryoneof
myenumsavalue.Whathappenswhenyouleavesomeinthemiddleofunsortedvalues
withoutvaluesassigned?

1.12 ProgrammingAssignment4
Eithermodifythisprogramorcreateyourown. Createtwodifferentenums,one
withabunchofnumbersassignedbeforeandafterinnoparticularorder,butleaving
three or four named enumerations without values assigned in the middle. For your
secondenumleavethemattheend.HaveyourprogramprintoutallvalueslikeIdid.
Seewhatgetsassignedbythecompiler,andifitevencompiles.

1.13 ProgrammingAssignment5
Enumsarejustplainweird.Allofthedocyoureadonlinetellsyouthattheywill
defaulttopublicaccessnomatterwhatyoudo.Taketheprogramswecreatedearlierto
testthevariousaccessmethodsandaddenumseverywhere. Identify all oftheplaces
wherethepublicnatureofanenumoverridesitsenclosingsecurity.

1.14 Properties
Herewehaveanamewhichcameaboutsimplybecausemarketingwantedanew
buzzword.InthedaysofC++wehadmembervariables.Allmembervariableswere
supposedtobeprefixedbym_soitwasobvioustoanyonereadingthecodeyouwere
talkingaboutamembervariable.Mostoldtimers,myselfincluded,couldn'treallybring
themselvestoconsistentlyusem_infrontofourmembervariables.Eventuallythere
weremanyIDEswhichwouldnotonlyforcethethinginfront,butwouldautomatically
generateasetandagetmethodforthevariable.SomeshopsmusthaveaverystrictIDE
combinedwithagroupofformerNaziSSofficersheadingupthecodereviews,because,
yes,alloftheircodefollowstheconvention.Therecodeisalsounreadable.

102

Chapter1Fundamentals

Namesalsostartedtocarrywarts.Actually,mostofthewartscamefromhabitsof
daysgoneby.AnyprogrammerwhogrewupworkingwithBASICwasusedtoseeinga
$attheendofavariabletoindicateastring,a%toindicateaninteger,andnothingto
indicate a floating point that is, at least until we created record definitions with
genderneutralnames.InBASICyoucouldchangethetypeofa%fromINTEGERto
LONG,butyoucouldnotchangeittofloatingpointwithouttakingthe%offtheend,
the compiler simply wouldn't allow it. Windows programmers adopted an incorrect
interpretationofHungarianNotationfornamingtheirvariables.
TCHAR
bool
unsigned long
void*
MyObject**

szMyChar[STRING_SIZE];
bMyBool;
ulMyLong;
pMyPointer;
ppMyObjects;

IhavehadtoreadandwriteIdon'tknowhowmanylinesofstuffwhichlookedlike
thisovertheyears.Someusedthisnamingconventionandthem_prefixformember
variables.Thelongerthevariablename,themoreunreadablethingsbecame.
m_udMaximumDailyWithdrawlLimitForAccount
Isn'tthatjustalovelyread. Thingsgotabituglierwhenitcametosystemlevel
documentation.Yousee,DOS/WindowswasanOSwhichwasjustkindofhackedat
withoutanyrealdesign.WhenyouworkwitharealOSwhichhadrealdesigndoneup
front,youhavesystemsdocumentationwhichlookslikethis:
FDV$GETAL(

OPTIONAL STRING text BY DESC [write],


LONG terminator BY REF [write],
STRING start_field BY DESC [read],
LONG start_index BY REF [read])

Manyofyouwillrecognizetheaboveasthelanguageindependentdocumentation
fortheFMSGETAL()functionasfoundintheOpenVMSapplicationdevelopmentbook
ofthisseries. EachlineliststheOSnativedatatype,adescriptivename,thepassing
mechanism,andin[]attheend,thetypeofaccessthefunctionrequirestothisparticular
pieceofdata.(BYDESCmeansbydescriptorwhichisanOSspecifictypesafeand
securemethodofpassingparameters.)

Chapter1Fundamentals

103

Onlesser platforms where thedocumentation creators were writing foronly one


language,itwasnotuncommontoseeanaccesswartprefixedtotheotherwartsfor
parameters.
rw_udMaximumDailyWithdrawlLimitForAccount
ManyC++programmerssimplyusedC++asabetterC. Sinceallstructmember
variables had public access, they simply declared all member variables public and
completelyskippedtheneedforsetterandgettermethods.
Javatriedtoimproveonbycallingeachmembervariableaclasspropertyandin
somecirclestheycalledthemobjectpropertiesreasoningthatonlystaticonescouldbe
calledclassproperties. FurtherconfusionwasaddedbyJavawhenitextendedits
HashtableclasstocreateaPropertiesclass.ThepurposeofthePropertiesclasswasto
allow string pairs of property and value to be stored via some semipermanent
method.
Serious insult to injury happened when the various platforms started allowing
applications to save application properties in various locations and files. Each
applicationwouldsavethingslikethecurrentwindowsizeandpositiononthedisplay,
colorand/orcolorschema,andvarioususerconfigurationvalues.Whenyouasauser
startedtheapplicationagainitcamebackupexactlywhereyoucloseditdown.Inmany
cases,especiallywithtesteditors,itwouldevenopenupthesamefileandputthecursor
backtotheexactsamespotyouwereonwithyourcompletedoandundohistoryloaded.
Microsoft must have combined the teams which gave us Microsoft Money,
Microsoft Bob, and Windows Vista when they decided to put together a crack
technicalteamtocomeupwithhowtheywantedtohandleproperties. Onceyousee
whattheydidwithPropertiesyouwillreadilybelievethatallMicrosoftproductshave
hideousamountsofcodebloat.Hereyoudeclareallofyourmembervariablesprivate,
then create aproperty withadifferent name which mayprovide aget() and/orset()
method. If the property has only aget() method, itisconsidered readonly. These
methodsarenowcalledaccessors.Theylookweirdandfunctionlikespecialtyclasses.

104

Chapter1Fundamentals

wine.cs
1 using System;
2
3
4
class Wine
5
{
6
private string m_wineType;
7
private string m_wineMaker;
8
private double m_usGlasses;
9
private double m_ukGlasses;
10
11
public string Wtype
12
{
13
get { return m_wineType;}
14
set { m_wineType = value;}
15
}
16
17
public string Maker
18
{
19
get { return m_wineMaker;}
20
set { m_wineMaker = value;}
21
}
22
23
public double Ml
24
{
25
get { return m_ukGlasses * 125.0; }
26
set { m_usGlasses = value / 250.0; m_ukGlasses = value / 125.0; }
27
}
28
29
public double UKGlassCount() { return m_ukGlasses;}
30
public double USGlassCount() { return m_usGlasses;}
31
}
32
33
class Program
34
{
35
static void Main(string[] args)
36
{
37
Console.Out.WriteLine("Hello World!");
38
Wine Chardonnay = new Wine();
39
Wine Merlot = new Wine();
40
41
Chardonnay.Wtype = "Chardonnay";
42
Merlot.Wtype = "Merlot";
43
44
Chardonnay.Maker = "Charles Shaw";
45
Merlot.Maker = "Carlo Rossi";
46
47
Chardonnay.Ml = 750;
48
Merlot.Ml = 5000;
49
50
Console.Out.WriteLine(

Chapter1Fundamentals
51
52
53
54
55
56
57
58

105

"You have {0} US glasses of {1} Chardonnay",


Chardonnay.USGlassCount(), Chardonnay.Maker);
Console.Out.WriteLine(
"You also have {0} UK glasses of {1} Merlot",
Merlot.UKGlassCount(), Merlot.Maker);
}
}

roland@linux-c345:~/mega_Mono> mcs wine.cs


roland@linux-c345:~/mega_Mono> Mono wine.exe
Hello World!
You have 3 US glasses of Charles Shaw Chardonnay
You also have 40 UK glasses of Carlo Rossi Merlot

You may find it difficult to believe, but a lot of effort went into creating this
example. I needed to show you both the good and the bad when it comes to this
philosophy.Inreallifeapplicationsyouwillneedtokeepmultipleprivatemembersin
lockstepfromasingletransaction.Yes,Icouldhaveredesignedthistostoremilliliters
and done the conversion on the output, but that would have robbed you of a
programmingassignment.
WhatifthiswasarealinventoryobjectwhereitneededtotrackOnHand,OnOrder,
BackOrdered, CustomerBackOrdered, MTDUnitsSold, and 36 months of prior sales
history?I'vedonemanyinventorymanagementsystemsinmydayandifyouplanon
doinganythingremotelyresemblingorderforecastingorinventorymanagementthat's
theleastoftheinformationyouneed.Asinglecustomerorderwillneedtoeitherreduce
OnHandwhileincreasingMTDUnitsSold,oritwillincreaseCustomerBackOrdered,or
itcouldactuallymanipulateallthreeifyouonlyhadenoughinventoryonhandtodoa
partialfill.ThisphilosophyofPropertiesandaccessorsMicrosoftisfoistinguponus
hassomeincrediblyshortsightedflaws.

106

Chapter1Fundamentals

1.15 ProgrammingAssignment6
Part1:CreateaconstructorfortheWineclasswhichrequiresboththewinetypeand
makertobeprovided. Removethesetportionsoftheaccessorsforthesetwovalues.
Maketheobjectstoreonlymillilitersforinventoryanddothecountconversionsinthe
appropriatemethods.
Part 2: After you get the above working, add methods to clear the milliliter
inventoryandtoincrementit. Changethetestprogramtofeedinavariousmilliliter
amountsfromvariousbottlesasyouwouldwhencountinginventory,thenprintoutboth
glasscountsforbothwinetypes.
Part 3: Declare a private default constructor for the Wine class. Retest your
program. Doeseverythingstillworkcorrectlyordoyouneedtocallthenowprivate
defaultconstructoratthestartofyourconstructor?

1.16 ParameterPassing
We'vebeenpassingparameterstomethodsforawhile,butI'vetriedtokeepittoa
minimum. ThecleanestwayformetoexplainthiswouldbetocoveronlyC#atthis
timethensprinkleinsomeuglystuffattheendforseasoning.
C#alwaysdefaultstopassingbyvalue,butthevalueitchoosesisn'twhatyoumay
bethinkingofasavalueorthevalue.
Takeamomentandreallychewonthatstatement.
I'mserious.Therearemanybaddescriptionsanddefinitionsfloatingaroundonthe
WebwhenitcomestoC#parameterpassing.Worseyet,youwillfindmanyclever
descriptions which are legally correct, but not in the best interest of a new
programmer.

Chapter1Fundamentals

107

Sections 1.2 and 1.3 of this chapter spent quite a bit of time talking about the
hard/native/primitive/value data types, structures, and classes. Structures were
originallyusedtoformeorganizedcollectionsofprimitivedatatypesmuchlikerecords.
UnderC#theyhavemorphedintosomethingresemblinglightweightclasseswithone
criticaldifference. Astructisstillconsideredavaluedatatypedespiteitsclasslike
syntaxandcapabilities.
Surf around theWeband youwillfind manyplaces stating thatvalue types are
passed by value and objects are passed by reference. You will even find sample
programsprovingthestatement.Here'sthetruth:
Wine Chardonnay = new Wine();

ChardonnayisareferencetoaninstanceofaWineobjectwhichwascreatedbythe
newoperator.Chardonnayispassedbyvaluebydefault.Becauseitisareference,the
method/functionreceivingitreferencestheobjectinstancecreatedbynew. Ifwewere
toexplicitlypassChardonnaybyreference,wewouldbepassing areferenceofthis
reference. WecouldactuallychangetheobjectChardonnayreferencedinourcalled
method or function if we pass Chardonnay by reference. When the reference
Chardonnayispassedbyvaluethecallercanonlyuseormodifyvariousportionsofthe
objecttowhichChardonnayrefers. Thisexplanationholdstrueforallobjectsexcept
strings.C#/Monoreallybuggeredstringhandling.
Ifyouareshinynewtoprogrammingthatlastexampleisalottochew. Ifyou
startedoutprogramminginCwithpointers,thenhadreferencesaddedbyC++onlyto
havepointerstakenawaybyJava,thisisn'tsomuchforyoutoswallow.It'saroadwell
traveled,justwithdifferentsignsonitnow.DuringthedaysofC,wehadonlypointers.
UnlikeC++,neitherC#norJavasupportdefaultparametervalues.Bothlanguages
losttheabilitywhentheytossedheaderfilesoutoftheirlanguagespecification.InC++
thecompilerusestheprototypetofillindefaultvalueswhichwillbeusedatruntime.
BothC#andJavarequireadevelopertocreatedefaultparametervaluesbyoverloading.
Theoverloadingpracticeiserrorproneandquiteconfusing.

108

Chapter1Fundamentals

test_ptr.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

#include <stdio.h>
void change_it( int **a, int *b) {
*a = b;
}
void assign_it( int *a, int b) {
*a = b;
}
int main(){
int *x_ptr, x, y;
x_ptr = &x;
assign_it( x_ptr, 21);
printf( "x after first call %d\n", x);
assign_it( &x, 33);
printf( "x after second call %d\n", x);
y = 1;
change_it( &x_ptr, &y);
printf( "x after third call %d\n", x);
printf( "*x_ptr after third call %d\n", *x_ptr);
return 1;
}

roland@linux-c345:~/mega_Mono> gcc test_ptr.c -o test_ptr


roland@linux-c345:~/mega_Mono> ./test_ptr
x after first call 21
x after second call 33
x after third call 33
*x_ptr after third call 1

Theinterestingportionofthiscodeistheparameterlistforthetwosubroutines,
change_it()andassign_it(),foundatlistinglines3and7.Youwillnoticethattheactual
codeinsideeachsubroutineisidentical,but,asyoucanseefromtheoutput,drastically
differentthingshappenwhenthesubroutinesarecalled.(Anyfunctionwhichdoesnot
returnavalueiscalledasubroutinewhenprogramminginC.)Wepassapointertoa
pointerasthefirstparameterinchange_it(). Whenwesubsequentlychangethevalue
thepointerpointsto(remember*meansvalueat)whatwearereallychangingisthe
pointerinourmainmodule.C#hasthissameissueifyouforceareference.Itjusthas
troublewithstrings.

109

Chapter1Fundamentals
test_ref.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

using System;
class TestRef
{
void change_it( string a, string b) {
a += b;
Console.Out.WriteLine( "\ta from inside of change:
}

{0}",a);

void assign_it( ref string a, string b) {


a = b;
}
static void Main(string[] args)
{
string str1 = "original";
string str2 = str1;
TestRef t1 = new TestRef();
t1.change_it( str1, " and still the best");
Console.Out.WriteLine( "str1: {0}", str1);
Console.Out.WriteLine( "str2: {0}", str2);
t1.assign_it( ref str1, "New and Improved");
Console.Out.WriteLine( "str1 after assign_it: {0}", str1);
Console.Out.WriteLine( "str2: {0}", str2);
t1.change_it( str1, " but we kept what you liked");
Console.Out.WriteLine( "str1 after change_it: {0}", str1);
Console.Out.WriteLine( "str2: {0}", str2);
}
}

roland@linux-c345:~/mega_Mono> mcs test_ref.cs


roland@linux-c345:~/mega_Mono> Mono test_ref.exe
a from inside of change: original and still the best
str1: original
str2: original
str1 after assign_it: New and Improved
str2: original
a from inside of change: New and Improved but we kept what you liked
str1 after change_it: New and Improved
str2: original

110

Chapter1Fundamentals

Weneedtotalkabouttwothingshere.First,whenyouwanttopassaparameterby
refyouhavetoactuallyusetheref(orout)keywordasshownonlistinglines11and24.
C#isnotlikeC++whenitcomestoreferences,itwillnotautomaticallycreateonefor
you.Thesecondthingtonoticeisthatwereallyonlygotacopyofthestring.Every
shredofdocumentationIcanfindsaysstringisareferencedatatype,butthiscertainly
isn'treferencebehaviorasisshownbythehighlightedoutputlines.
Whathappenswhenyouusearealreferenceclass/object?
TestClassRef.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

using System;
class TestClass
{
public string txt;
}
class Program
{
void change_it( TestClass a, string b) {
a.txt += b;
Console.Out.WriteLine( "\t from inside of change:
}
void assign_it( ref TestClass a, TestClass b) {
a = b;
}
static void Main(string[] args)
{
TestClass tc1 = new TestClass();
TestClass tc2 = new TestClass();
TestClass tc3 = new TestClass();
Program p1 = new Program();
p1.change_it( tc1, "Original");
p1.change_it( tc2, tc1.txt);
p1.change_it( tc3, "spare parts");
Console.Out.WriteLine( "tc1 {0}", tc1.txt);
Console.Out.WriteLine( "tc2 {0}", tc2.txt);
Console.Out.WriteLine( "tc3 {0}", tc3.txt);
p1.assign_it( ref tc1, tc3);
Console.Out.WriteLine( "After assign_it");
Console.Out.WriteLine( "tc1 {0}", tc1.txt);
Console.Out.WriteLine( "tc2 {0}", tc2.txt);

{0}",a.txt);

Chapter1Fundamentals
38
39
40
41
42
43
44
45
46
47
48
49
50
51 }

111

Console.Out.WriteLine( "tc3 {0}", tc3.txt);


p1.change_it( tc1, " but we kept what you liked");
Console.Out.WriteLine( "After change_it");
Console.Out.WriteLine( "tc1 {0}", tc1.txt);
Console.Out.WriteLine( "tc2 {0}", tc2.txt);
Console.Out.WriteLine( "tc3 {0}", tc3.txt);
p1.assign_it( ref tc1, tc2);
Console.Out.WriteLine( "After assign_it");
Console.Out.WriteLine( "tc1 {0}", tc1.txt);
Console.Out.WriteLine( "tc2 {0}", tc2.txt);
Console.Out.WriteLine( "tc3 {0}", tc3.txt);
}

roland@linux-c345:~/mega_Mono> mcs TestClassRef.cs


roland@linux-c345:~/mega_Mono> Mono TestClassRef.exe
from inside of change: Original
from inside of change: Original
from inside of change: spare parts
tc1 Original
tc2 Original
tc3 spare parts
After assign_it
tc1 spare parts
tc2 Original
tc3 spare parts
from inside of change: spare parts but we kept what you liked
After change_it
tc1 spare parts but we kept what you liked
tc2 Original
tc3 spare parts but we kept what you liked
After assign_it
tc1 Original
tc2 Original
tc3 spare parts but we kept what you liked

Ourfirstclasssimplyhasastringmember element(orpropertyifyouinsiston
usingthenewlingo.)Becausewecreatedthisclasswithoutderivingitfromanyother
class, any declarations of it will be an honest to goodness reference without any
qualifiersspelledoutinfineprintlikethestringclasshas.

112

Chapter1Fundamentals

NoticethatourProgramclassnowcontainsthemethodsforchangingandassigning.
Instead of strings, most of the parameters are now an instance or reference of our
TestClass.Westillonlyforceareferencewiththeassign_it()method,butlookatthe
differenceinoutput!Thefirstcallassigningtc3totc1reallydidchangethereference.
Weknowthisbecausethelaterchange_it()callinvolvingtc1actuallychangedthevalue
intc3!Thefinalassignmentoftc1totc2provesbeyondadoubtwereallychangedtc3.
Whataboutthatobjectwecreatedoriginallyfortc1? It'sjustfloatingaroundout
therewaitingforourapplicationtorunlongenoughthatgarbagecollectionfindsit,or
thatourentireregioniswipedwhenourprogram ends. C#/Mono doesn'tgiveusa
methodofdeletingitunderprogramcontrol.ItdoesprovidetheIDisposableInterface
whichwouldletourclassimplementDispose(),however,thatmethodissupposedtobe
used for releasing nonmanaged resources. It does not actually free the managed
memoryusedbytheobjectinstance.(*seenextsection)
Inshort,the String classlugied upparameter passing because Microsoft triedto
make C#/Mono easier to learn for newbies. While String is a reference class, the
equalityandinequalityoperatorswereoverriddentocompareobjectvaluesinsteadof
objectreferences.IfyoucomefromaC++orJavabackground,youhavegottenusedto
String beingaclass which operates like allother classes. Since Microsoft wantsto
dumbdowntheIQlevelrequiredforprogramming,theymadetheclassStringbehave
somewhatlikeanativedatatype.
ThisisathrowbacktothedaysofBASICPLUSonthePDP11/70underRSTS/E.
ThisearlyversionofBASICallowedausertocreateastringvariablebysimplycoding:
200 B$ = My String

UberGeeksofthedayactuallyknewthatthefirstbyteofaBASICstringwould
storeanunsignedbinaryintegercontainingthelengthofthestringandtherestofthe
characterswouldoccursequentiallybehindthatbyteinmemorylikeanarray.Dynamic
stringscouldn'tbemorethan255bytesbackthen,buttheprogrammergottouseastring
asanativedatatype.

Chapter1Fundamentals

113

1.17 GarbageCollection,Destructors,andGUIToolkits
Theprevioussectioncontainsthemantrabeginnersaretaughttorecitefromday
one.TheyaresupposedtolettheC#/Monoenvironmentmakeallobjectdestructionand
resourcereleasingdecisions.Yes,therearecommandlineargumentswhichallowauser
tochangethegarbagecollectionengine,boundaryseparator,andeventhesizeofthe
nurserywhereobjectsarecreated,butapureC#/Monodeveloperisneversupposedto
doanythingwithgarbagecollection.
WouldyoubeshockedtolearnthatDotNot1.1addedtheIDisposableInterface
alongwiththeDispose()methodontopofclassfinalizers?Ithoughtnot.TheDispose()
methodcombinedwithafinalizerisarealhouseofcards. Inmostcasesifyouhave
Dispose()youshouldcallGC.SuppressFinalize(this).Why?Becausethereshouldbe
noexternalresourceslefttoreleaseonceDispose()isdone.
WhydidMicrosofthavetobowtotheindustry?Becausenomatterhowgreatyour
garbagecollectionalgorithm,onceanobjectneededunmanagedresourcesorpinned
memoryforusebyentitiesoutsideoftheenvironment,thereisnomethodofdefining
doneuntiltheprogramiscomplete.Whendealingwithdatabaseinterfacesthatcould
returnthousandsofrowswhichhadtobetranslatedintolocalspace,itsoonbecame
obviousthatgarbagecollectioncombinedwithadynamicallyexpandingVMcouldn'tfix
thisproblem.
One of the biggest tools employed by the various garbage collection engines is
relocation.Whendealingwithmanagedresources,thecollectionengineisfreetomove
or pack all of the existing objects together to free up a large or larger contiguous
memoryregionforobjectcreation. Whenmemoryinthisregionispinnedbecauseit
wasusedtotransferdataeitherintooroutofadatabasebuffer,thatmemorycannotbe
movedforthelifeoftheprogramunlesstheprogrammerhasamethodofinformingthe
environmenttheyaredonewiththememory.

114

Chapter1Fundamentals

Thanks to C#/Mono being a Java clone, a programmer cannot directly call an


object'sdestructororfinalizer. AcalltoDispose()isconsideredlighterweightthana
calltoafinalizer.Intruthitshouldbe.OnlyfreeresourcesallocatedoutsideoftheVM
andpinnedmemoryinyourDispose()method. Everythingelsewillautomaticallybe
takencareofbytheenvironmentwhenthetimecomes.Wedon'thaveagoodmethodof
telling the environment we are done with a C#/Mono object, so freeing up physical
resourcesisthebestwecando.
Dependinguponwhichcollectionengineyouselectandtheparametersyouprovide
on the command line, garbage collection may very well run before each and every
allocation.Icantellyoufromexperiencethatyoudefinitelydonotwantthattohappen
if your program has any size or does anything real. The runtime becomes
excruciatinglylong.
MuchliketheJavaJNIkit,C#/MonoprovidesuswithGC.Collect(). Youdonot
everwanttoinvokethisinyourapplication.Ifthereiseventheslightestinstabilitywith
howyouorathirdpartylibraryhandleexternalresources,callingthismethodisastack
dumpwaitingtohappen.YouneedtoimmediatelycallGC.WaitForPendingFinalizers()
whichwillreleasecontroltothethreadswhichhaveanobjectidentifiedforgarbage
collection.
YoumayhavenoticedthatIhaveyettocreateadestructorforyou.EventuallyI
will,butnotrightnow.AdeveloperneedstocreateadestructorforaC#/Monoclass
onlywhentheyallocateresourcesoutsideoftheruntimeenvironment.Wheneveryou
openafileondiskviaanonC#/Monotool,connecttoadatabase,allocateaport,call
OS native services, etc. you need to create a destructor for your class to ensure all
resourcesarereleasedbacktotheOS.TheMono/C#environmentisnotgoingtomake
anyattemptsatreleasingyourexternalresourcesuntilafteryourprogramcompletesorit
absolutelyhastoduetotheageandsizeoftheobjectwhichallocatedthem.

Chapter1Fundamentals

115

Manyofyounewtothefieldwillbeshockedtohearthis,butoneofthemain
decisionpointswhenchoosingaGUItoolkitishowwellitcleansupafteritself.Iknow,
mostofyouwillbeclamoringthatitshouldbebasedonfeatures,orthelook&feel
beingconsistentwithwhateveryouarecurrentlyusing,butthatwouldbethereason
MBAsandnewbieschoosetoolkits.Theprofessionaldeveloperchoosesatoolkitbased
uponhoweasyitmakeshisorherprogramminglifeandhowwellitstopsbugsfrom
gettingtoproduction.
Ifyouhave doneanyprogramming intheC++ world within thepast five years
you'vebeenhearingaboutatoolkitcalledQtwhichisnowownedbyNokia.Thistoolkit
hasboth anOpenSource andacommercial version. TheOpenSource version was
chosentobethemainlibraryusedbytheKDesktopdevelopers(morecommonlycalled
KDEdevelopers)whichaddedthousandsofdeveloperstotheQtproductthesecondthe
decisionwasmade.Trolltech,theownersatthetime,wereveryreceptivetotheOpen
Sourcecommunitysoalargeamountofcodeproducedbythatcommunitymadeitinto
thebasetoolkit.
It'snotfairtocallQtaGUIlibrary. Itisacomplete applicationtoolkithaving
genericclassesforflatfilesanddirectsupportformanydatabaseformatsalongwitha
greatscreen/formsdesigner. Theonlythingitdoesn'thaverightnow,butI'mtoldis
beingworkedon,isareportwritercomponentlikethatofCOBOL.
With all this time spent singing the praises it should not surprise you that two
different MonoQtpackages exist. Thefirst isQyoto. Thisisput out by the KDE
developersandhasexceptionalsupportforDoxygen.ThesecondisQt4Dotnetanditis
basedontheQtJambiJavabindingswhichareofficiallysupportedbyNokia.
I don't see these two particular tools ever merging while Qt is still actively
developed.WhenQt4wascomingoutitwasamassivechangefromQt3.Evenwith
backward compatibility turned on,mostQt3basedprograms ceased tofunction. As
KDEgetsmoreandmorecomponentsitwilltakelongerandlongertofullymigratetoa
newQtrelease.ThusitmakessensetohavetwodifferentQtusagelibraries.

116

Chapter1Fundamentals

Besidestheinventionofsignals&slots,Qtaddedalevelofapplicationstabilitythe
industryhasneverbeforeseenwithatoolkit. Therootobject/classwhichisusedto
deriveallotherclassesunderitkeepstrackofallclasseswhicharederivedfromitand
instantiated.Thedestructorforthisobjectwalksdownthatlistatprogramconclusion
andnukeseverythingwhichhastodowiththeQtlibrary.
SomeofyoumaythinkitisnobigdealthataGUIlibrarycleansupbehinditself,
butQtisanApplicationdevelopmentlibrary.Ithasclassesforflatfiles,hashedfiles,
databasesandmore.IhavetesteditmanytimesandcovereditinTheMinimumYou
NeedtoKnowAboutQtandDatabases,soIcantellyouwithcompletehonestythatQt
really does close all connections and clean things up quite well. Given the design
philosophysupposedlybehindC#,thatitshouldcleanupbehindaprogrammerandstop
allresource/memoryleaksfromhappening,Qtfitsinquitenicely.
Gtk# is the C# GUI toolkit in widest use today. That is also the toolkit
MonoDevelop(theOpenSourceMonoIDE)iswrittenwith.GtkisthedefaultGnome
toolkit,buttheUbuntuGnomedevelopershavemadeapublicdecisiontouseQtfrom
nowon.Qthastheabilitytoemulatethenativelookandfeelonanytargetplatform,so
youreallycanwriteonceandcompileforalltargets.(Yes,youcanforceacustomlook
andfeelandmaintainitonalltargetsifyouwish.)
Ifyouwanttoplanforthefuture,youwilluseoneoftheQtbasedtoolkits. The
only downside isthatsignals andslots havenot beenfully ported totheDOTNOT
environmentatthetimeofthiswriting.Theupsideisthatyourapplicationwillhavea
nativelookandfeelnomatterwhatplatformitrunson.

Chapter1Fundamentals

117

1.18 Namespacevs.Package
AfterthebrutalonslaughtofinformationI'veprovidedinthischapterthissection
will seem rather anticlimactic. For the most part, a namespace and a package are
simply a way of grouping definitions into controllable entities: Either allows you to
importasingleclass/itemortheentiregroup. Theonlyrealdifferenceisthenaming
conventionforJavadictatesthedirectoryandJARstructurebecausetheJVMusesthe
actualnameasapathwhenitgoeshuntingthroughitsdirectoriesandJARS.
C#simplyusesthenamewhenitgoesrummagingthroughtheDLLsitknowsabout.
Rememberourpriorexamples.WehadtolinkeveryDLLandSOspecifically.Your
EXEfilealreadyknowsexactlywhichfileitwantsandfirstlooksinthesamedirectory
astheEXE,thenthefewotherplacesitknowsabout.

1.19 StatementsandStyle
I'mnotgoingtowastealotofpapercoveringthesamelogicandcontrolstatements
wewillbeusingextensivelyintheexampleprograms.Thisisn'tasyntaxreference,it's
a jump start for skilled programmers. Suffice itto say thatC#/Mono has thesame
while(),dowhile(),andfor()loopsweareusedtousingwithasubtletwistortwo.Ithas
thesameifstatementsandswitchstatements,justnofallthroughonthecases.
Mostimportantly,youshouldnever,underanycircumstancesusethefollowing:
a = (b > 0) ? b : 0

Thisisverybadcodingstyleandthereissimplynoexcusepossibleforit.Ifyou
wanttohackoutcodethatlooksliketheworstPerleverwritten,thenplease,goworkin
Perlandleaveusalone!
Anotherstatementyoumayfindincodeisthenullcoalescingoperator. Imay
actuallyhavetothanksomeoneatMicrosoftforcreatingthisoperator.Itremovedmost
oftheuglyreasonspeopleusedtojustifythedecisionoperator(?:)thatwejustdiscussed
andmakescodeabitmorereadable.Whenyouaren'tworkingwithreferencetypesthe
syntaxcanbeabitfreaky,especiallyforC++programmers.

118

Chapter1Fundamentals

int? k = null;
int j = k ?? -2;

Inpart,I'mnotcertainIliketheideaofusinganoperatortoextendthevalidrange
ofvaluesforanativedatatype,but,Icanseethepoint.Theymostlikelykeepaspecial
flagwhichgetssetwhenyoudeclareint?.ThefreakypartisthatC++programmers
usedtodeclarereferencevariablesbyplacing&attheendofthedatatype,soaquick
readcouldleadtoconfusion.
IfyouprogrammedinJava,youareusedtoseeingsyntaxlikethis:
for( float j : studentGradeArray)
sum += j;

Well,C#changedthesyntax:
foreach( float j in studentGradeArray)
sum += j;

I'msympathetictothenewverb,but,ifyoudomuchembeddedSQLormanystored
procedures,youwillbeginhavingdifficultyasforeachexiststhere,buthasdifferent
syntax.
WemightaswellfinishthissectionbystatingthatC#hasthesametrycatchfinally
errorhandlingstructuresthatbothC++andJavahad.

Chapter1Fundamentals

119

1.20 Summary
C#/Monocametousoutofaflurryoflegalbattlesandheatedwordsinthepress
between twolarge corporations. Microsoft, having readthe writing onthewalland
realizingithadlessthan10yearsleftasacorporation,desperatelytriedtobindthe
wildlypopularJavaplatformtoitslegacyWindowsplatform(whichstartedoutasthe
WindowsApplicationunderDOS,despitethefraudulentpackagelabeling)tosqueeze
outafewmoreyearsofcorporateearnings.Microsoftlostitslegalbattlesandquickly
rebadged its Java compiler as C#, tweaking a few things here and there. To make
Internetdevelopmenteasiertheyalsocreatedatoolsetcalled.NETwhichmuchofthe
industrypronouncesDOTNOTjusttotweakthem.
It should benoted that a fewof the more famous Microsoft people are pouring
money, information, and resources into the Mono project. Windows will soon bea
memoryintheITworld,likeWang,Singer,andXeroxPark,butunlikethem,willnot
haveleftitsmarkontheindustryunlessMonosurvivesonthenewdesktopplatforms
and gets migrated to the mainframe platforms (which are now your robust database
serverplatforms.)
Since Java has the feeling it was written by SUN so they could make use of
programmersthatcouldn'tlearnallofC++,itshouldcomeasnosurprisethatJavastole
heavilyfromC++whichabsolutelythievedfromC.C#,beingamassivecloneofJava,
then,byextension,alsothievedfromCandstoleheavilyfromC++. Thejustification
youwillheartimeandtimeagainisthateachcreatorwantedtheirlanguage/tooltobe
quickly adopted, so, it had to mimic the syntax of the most popular programming
languageontheplanetatthetime.Keepinmindmostpopular!=mostlinesofcode
inproduction!=mostcorebusinesssystemswrittenin.Despiteallofthemarketing
dollarsspenttotryandchangeit,Mostlinesofcodeinproductionhonorsstillbelong
toCOBOLandwillatleastuntilY3K.

120

Chapter1Fundamentals

HopefullyC#/MonowillbethelastblatantripoffweseeoftheClanguage.Before
youallgetupinarmsrememberthatI'vebeeninthisindustrysincebeforeCburstonto
thescene. Yes,I'vewrittenmountainsofcodeinitandenjoyedmuchofit. Mypet
peeveisthatnoweverylanguagelooksthesameanditisgettingextremelydifficultfor
language syntax highlighters to be developed for text editors. You are one or two
languageripoffsawayfromlosingallofyourgoodtools.
Today,whenyouseeasnippetofcodeinamagazinearticle,youactuallyhaveto
readthearticletofindoutwhatlanguagetheyareusing,unlessyouhappentoseeoneof
thekeydifferences:

JavausesSystem.out.println()whileC#/MonousesConsole.Out.Writeline()and
C++usessomethinglikeout<<butcouldalsousetheCprintf()statementand
itsvariations.

C++usesa;aftertheclosing}foraclassdefinition,butneitherJavanorC#
do.

C++andC#havepointers,thoughtheyaredeclareddifferently,butJavadoes
not.

C#,todate,istheonlyoneoftheselanguageswiththenullcoalescingoperators
of?And??.

OnlyC++supportsdefaultparametersinasinglemethoddeclaration.

Yes,therewillbemanyothersubtletiesifyouarereallypayingattention,butjust
howoftenarepeoplepayingthatcloseofattentiontoasnippetinamagazine?
UntilrecentlyMonohadtheseverelimitationofonlysupportingtheGtk#interface.
WhilethismadefornaturallookingapplicationsontheGnomedesktop,itmadefor
someoddlookingstuffeverywhereelse. Thankfullytherehavebeeneffortstobring
forthQtwhichemulatesthenativelookandfeelofeveryplatformitrunsonunlessyou
physicallyforceittohaveadifferentlookandfeel.

Chapter1Fundamentals

121

C#/Mono has some incredibly weird default protection rules. Default protection
withinaclassorstructis private,butwithina namespace is internal. WithC++the
defaultprotectionwithinaclassisprivatebutwithinastructispublic.C++doesnot
have a default namespace level protection. When it comes to Java, the default (no
modifier)protectionlevelispackageprivate.
Inshort,theconfusionyoufeelisreal.Theselanguagesaresosimilarinsyntaxthat
itisnearlyimpossibletotrylearningallthreewithinashortperiodoftime. UntilQt
entered the world of C++, most veteran C++ programmers did not use an IDE
(Integrated Development Environment.) When Mono entered the scene, and IDE
becamemandatory,butnowthatQtisavailableforMono,wearebacktobeingableto
useregulareditorsagain.

1.21 Exercises
1. Whenyoufinishdeclaringaclass,doesC#/Monorequireyoutoenditwitha
";"?
2. WhatbitwiseoperatordoesMonohavethatC++doesnot?
3. Whatisthesmcscommandusedtocreate?
4. WhatmaindifferenceistherebetweenaclassandastuctinC#/Mono?
5. Whatprogramminglanguagehasthemostlinesofcodeinproductiontoday?
6. There is only one C#/Mono protection level which cannot be accessed by a
derivedclassinthesamecompilationunit,whatisit?
7. WheremustyoudeclareaconstantinMono?InC++?
8. WhoputsoutQyotoandwhatisit?
9. Whatisthemaximumpositivevaluea16bitsignedbinaryintegercanhold?
10. Whenyouwantthemcscommandtocreatealibrary,what2(two)switches
mustbeused?

122

Chapter1Fundamentals

11. WhatdoesLITTLE_ENDIANmean?
12. InMono,whathappenswiththisequationifmis7:(m++==7)||(n++==4);
13. DoesC#/Monoallowyoutodriveastructfromanotherstruct?
14. Do Mono and C use the same data type for Double when using the GNU
compileronLinux?
15. Whatisthe"nullcoalescing"operator?
16. WhatisreturnedbyacalltoJavanextInt()whenyoudon'tprovideamaximum
value?
17. WhatisPackedDecimal?
18. What is the only reliable method of transfering C# Decimal data between
machinetypes?
19. Whatdoes:int*x1,x2,x3;declareinMono?InC++?
20. Whatarethetwomethodsof"pinning"amemoryallocationtoactualphysical
memory?
21. CanyoudeclarebothpointervariablesandentityvariablesinthesameMono
declaration?
22. HowdoyouraiseanumbertoapowerinMono?InC++?
23. WhatisthedefaultprotectionforC#/Monothingsdeclaredoutsideofaclassor
structbutwithinanamespace?
24. WhatistheC#/Monoruleofthumbwhenitcomestodefaultprotection?
25. WhatsourcecodedocumentationtoolshouldyoubeusingwithC#/Mono?
26. WhatisthedefaultstorageformatforMySQLonmostplatforms?
27. DoesC#/Monoprovidenativeindexedfilesupport?

Chapter1Fundamentals

123

28. If you read and write data to/from its source via SQL does that mean
transactionsmustbesupported?
29. WhatisthedefaultprotectionforC#/Mono declarations occuringinsideofa
classorstuct?
30. Howis"ProtectedInternal"reallyread?
31. IfyoudeclareyourC#/Monoclasspublic,canyoudeclareyoursettermethods
private?
32. WhatC#/Monoprotectionleveldoyouassignwhenyouonlywantotherclass
memberstohaveaccesstoanitem?
33. What system method must immediately follow the call to force garbage
collection?Why?Whatdoesthismethoddo?
34. How do you indicate which library or libraries you wish to use on the mcs
commandline?
35. What one file does the Mono runtime automatically look for in the same
directoryastheexecutablefile?
36. Whatisthesyntaxforaloopwhichprocesseseachelementofafloatarray?
37. InMono,howdoyouprototype aCfuction named amort_1() whichreturns
doubleandexistsinMyLib?
38. WhatisreturnedbyacalltoJavanextInt()whenyoudoprovideamaximum
value?
39. WhatdoesC#/Monocallget()andset()methodsforproperties?
40. DoesC#/Monosupportdefaultparameters?
41. WhatkindofdatatypedoesC#/Monoconsiderastruct?
42. WhenwritingafunctioninC++whichwillbecalledfromMono,howmustyou
declareit?

124

Chapter1Fundamentals

43. If your class implements IDisposable, what system call should be in your
Dispose()method?
44. ShouldaclasshavebothaDispose()methodandafinalizer?Whyorwhynot?
45. WhatbenchmarkdoesadeveloperusetochooseaGUIorothertoolkit?
46. WhatdoesthefPICswitchtelltheGNUcompilertodo?
47. WhatsingleactmakesmostC#/Monocodenonportable?
48. Wheremustthe[]beplacedwhendeclaringanarrayinMono?
49. WhoputsoutQt4DotNetandwhatisit?
50. Whenmustyoucreateadestructorforyourclass?
51. Howdoyouforcepassingaparameterbyreference?
52. DoesC#/Monoallowyoutochangethebasedatatypeofanenum?
53. WhatshouldyourDispose()methoddo?
54. WhatistheprimarymethodofQtobjectcommunication/interaction?
55. WhatistheonlywaytopotentiallygetanegativenumberfromtheMonoNext()
function?
56. WhatsystemcalldoesC#/Monoprovidetoforcegarbagecollection?
57. WhatisthedefaultparameterpassingmethodofC#/Mono?
58. WhenmustyouimplementIDisposableandincludeaDispose()methodinyour
class?
59. What3GLprogramminglanguage hasaReportWriterwritten intoitsANSI
standard?
60. What isoneofthebiggest tools employed bythevarious garbage collection
methods?Why?

Chapter1Fundamentals

125

61. Whenaparameterdeclarationcallsforareferenceinsteadofavalue,willC#
automaticallyconvertavaluelikeC++?
62. Giventhefollowing:WineChardonnay=newWine();WhatisChardonnay?
63. WhatistheonlymethodofimplementingdefaultparametersinC#/Mono?

You have been reading a preview. To learn more about this award
winning book series and find out how to purchase works by this author
please visit http://www.theminimumyouneedtoknow.com

You might also like