• No results found

Introduction to C# Programming and the.net Framework: (PDF)

N/A
N/A
Protected

Academic year: 2021

Share "Introduction to C# Programming and the.net Framework: (PDF)"

Copied!
277
0
0

Loading.... (view fulltext now)

Full text

(1)

Introduction to C# Programming and the .NET Framework: (PDF)

Lesson 1: Introduction

Underst anding t he Learning Sandbox Environment T he OST Plug-In

Let 's Do Somet hing!

Closing and Reopening a Solut ion St udio IDE

A Quick T our

Creat ing Your Second Project Programming Code

T he Source Code Window

Lesson 2: Statements, Keywords, Scope, T ypes, Variables, and Conversions Programming St at ement s

Ident if iers and Reserved Words Scope

Scope Def init ion Local Scope Block Scope Class Scope Scope Import ance Dat a T ypes

Built -In T ypes

Lesson 3: Expressions, Precedence, and Assignment, and Increment/Decrement Operators Programming Expressions

Assignment s and Assignment Short cut s Simple Assignment Operat or

Compound Assignment Operat ors

Mat hemat ical Compound Assignment Operat ors Bit wise and Shif t Compound Assignment Operat ors C# Operat ors and Precedence

Increment and Decrement Operat ors

(2)

Lesson 5: Branching Statements: Conditional and Unconditional Uncondit ional Branching

Condit ional Branching

Lesson 6: Iteration (Looping) T he For Loop

T he While Loop T he Do..While Loop

For Loop Versus While Loop Put t ing Looping T o Work

Lesson 7: Input and Output Statements

Windows GUI Applicat ion Versus Console Applicat ion Simple Console Input and Out put

GUI Input and Out put

Lesson 8: File Input and Output Using File Object

Using St reams

Lesson 9: Models, Classes, and Objects Object -Orient ed Programming Const ruct s

Models: A World View

Classes: A Blueprint and More Example: T he Alphabet Aquarium Classes: A New Dat a T ype

Object s: A Mult iplicit y of Inst ances

(3)

Lesson 11: Methods, Return T ypes, and Constructors Met hods

Class Funct ion Members Class Met hods

Access Modif iers Met hod Paramet ers Met hod Ret urn T ypes Coding: Camel I

T he ref Keyword and Passing By Value Versus Passing By Ref erence Class Const ruct ors

Lesson 12: Initializers, Object Initializers, and Anonymous T ypes T ypes of Dat a T ypes

Value Dat a T ypes Ref erence Dat a T ypes Boxing and Unboxing T he new Keyword

Object Init ializat ion

Const ruct ors and Object Init ializat ion Accessors and Object Init ializat ion Object Init ializers

Aut omat ic Propert ies

Coding: T he Employee Dat abase Anonymous T ypes

Popup Forms and Dialogs

Lesson 13: T he this Keyword, Static and Instance Members Class Inst ances

Inst ances

Self -Ref erencing Using t he 't his' Keyword Coding: Boxing

St at ic Members and Classes St at ic Keyword

Class Inst ances Versus St at ic Inst ances

(4)

Lesson 14 : Finalizing Objects, and Memory Concepts (Stack versus Heap) Comput er Memory

Comput er Memory and Allocat ion St ack Versus Heap

Garbage Collect ion

Finalizing Object s and Dest ruct ors Coding

Lesson 15: Overloading Methods, Overloading Operators, and Returning Multiple Values Using out

Overloading

Met hod Overloading Operat or Overloading Coding

T he out Keyword

Paramet er Modif ier Review T he out Paramet er Modif ier

Met hod Fingerprint /Signat ure and Paramet er Modif iers Mult iple Ret urn Values Using out

Coding

Lesson 16: Debugging

A Sample Debugging Program

Breakpoint s, Expression Evaluat ion, and Wat ches

(5)

Lesson 17: One-Dimensional Arrays, the f oreach Keyword, Initializing, and the params Keyword

Array Fundament als What Is An Array?

Array Declarat ion, Allocat ion, and Init ializat ion Accessing Array Element s

Coding

Advanced Array T opics Array Assignment s

Array It erat ion and t he f oreach St at ement T he params Paramet er Modif ier

Anonymous Arrays Course Project

T he Assignment T he Mat erials

Coding Requirement s T he Milest ones T est ing

Hint s

Copyright © 1998-2013 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

(6)

Introduction

Introduction to C# Programming and the .NET Framework: Lesson 1

Course Objectives

Welco me to the O'Reilly Scho o l o f Techno lo gy Int ro duct io n t o Obje ct -Orie nt e d Pro gram m ing Using C# co urse!

In this co urse yo u will gain a deeper understanding o f o bject o riented pro gramming. Yo u will learn abo ut data types and sco pe, and create pro grams using mo dels, classes, o bjects, metho ds, and co nstructo rs, as well as the ways in which these elements relate to o ne ano ther. File Input/Output (I/O) to pics are also co vered, allo wing yo u to bo th read fro m and write to files. As yo u create increasingly co mplex pro jects, yo u will learn ways to debug yo ur co de as well.

Upo n co mpletio n o f this co urse, yo u will be able to :

Pro gram C# statements, identifiers, expressio ns, and assignments Apply relatio nal, bo o lean, and bitwise lo gical o perato rs

Branch and iterate C# co de

Differentiate between Windo ws GUI and Co nso le applicatio ns Define o bject-o riented mo dels, initializers, and class relatio nships

Demo nstrate kno wledge o f o verlo ading and memo ry co ncepts such as stack and heap Debug pro grams using breakpo ints, expressio n evaluatio n, and watches

Yo u will create several applicatio ns thro ugho ut the co urse, which will enhance yo ur pro fessio nal po rtfo lio and also co ntribute to ward certificate co mpletio n.

Note

This lesso n duplicates the first two lesso ns o f the first co urse. If yo u to o k that co urse, yo u may either skip this lesso n, o r bro wse thro ugh it to refresh yo ur kno wledge o f the material. Ho wever, yo u sho uld still co mplete the ho mewo rk to pro ve yo u kno w the material—and to get yo ur certificate fo r this co urse!

Learning with O'Reilly School of Technology Courses

As with every O'Reilly Scho o l o f Techno lo gy co urse, we'll take the useractive appro ach to learning. This means that yo u (the user) will be active! Yo u'll learn by do ing, building live pro grams, testing them and experimenting with them—

hands-o n!

To learn a new skill o r techno lo gy, yo u have to experiment. The mo re yo u experiment, the mo re yo u learn. Our system is designed to maximize experimentatio n and help yo u learn to learn a new skill.

We'll pro gram as much as po ssible to be sure that the principles sink in and stay with yo u.

Each time we discuss a new co ncept, yo u'll put it into co de and see what YOU can do with it. On o ccasio n we'll even give yo u co de that do esn't wo rk, so yo u can see co mmo n mistakes and ho w to reco ver fro m them. Making mistakes is actually ano ther go o d way to learn.

Here are so me tips fo r using O'Reilly Scho o l o r Techno lo gy co urses effectively:

T ype t he co de . Resist the temptatio n to cut and paste the example co de we give yo u. Typing the co de actually gives yo u a feel fo r the pro gramming task. Then play aro und with the examples to find o ut what else yo u can make them do , and to check yo ur understanding. It's highly unlikely yo u'll break anything by

experimentatio n. If yo u do break so mething, that's an indicatio n to us that we need to impro ve o ur system!

T ake yo ur t im e . Learning takes time. Rushing can have negative effects o n yo ur pro gress. Slo w do wn and let yo ur brain abso rb the new info rmatio n tho ro ughly. Taking yo ur time helps to maintain a relaxed, po sitive appro ach. It also gives yo u the chance to try new things and learn mo re than yo u o therwise wo uld if yo u blew thro ugh all o f the co ursewo rk to o quickly.

Expe rim e nt . Wander fro m the path o ften and explo re the po ssibilities. We can't anticipate all o f yo ur questio ns and ideas, so it's up to yo u to experiment and create o n yo ur o wn. Yo ur instructo r will help if yo u go co mpletely o ff the rails.

Acce pt guidance , but do n't de pe nd o n it . Try to so lve pro blems o n yo ur o wn. Go ing fro m

(7)

Acce pt guidance , but do n't de pe nd o n it . Try to so lve pro blems o n yo ur o wn. Go ing fro m misunderstanding to understanding is the best way to acquire a new skill. Part o f what yo u're learning is pro blem so lving. Of co urse, yo u can always co ntact yo ur instructo r fo r hints when yo u need them.

Use all available re so urce s! In real-life pro blem-so lving, yo u aren't bo und by false limitatio ns; in OST co urses, yo u are free to use any reso urces at yo ur dispo sal to so lve pro blems yo u enco unter: the Internet, reference bo o ks, and o nline help are all fair game.

Have f un! Relax, keep practicing, and do n't be afraid to make mistakes! Yo ur instructo r will keep yo u at it until yo u've mastered the skill. We want yo u to get that satisfied, "I'm so co o l! I did it!" feeling. And yo u'll have so me pro jects to sho w o ff when yo u're do ne.

Lesson Format

We'll try o ut lo ts o f examples in each lesso n. We'll have yo u write co de, lo o k at co de, and edit existing co de. The co de will be presented in bo xes that will indicate what needs to be do ne to the co de inside.

Whenever yo u see white bo xes like the o ne belo w, yo u'll type the co ntents into the edito r windo w to try the example yo urself. The CODE TO TYPE bar o n to p o f the white bo x co ntains directio ns fo r yo u to fo llo w:

CODE TO TYPE:

White boxes like this contain code for you to try out (type into a file to run).

If you have already written some of the code, new code for you to add looks like this.

If we want you to remove existing code, the code to remove will look like this.

We may run pro grams and do so me o ther activities in a terminal sessio n in the o perating system o r o ther co mmand- line enviro nment. These will be sho wn like this:

INTERACTIVE SESSION:

The plain black text that we present in these INTERACTIVE boxes is

provided by the system (not for you to type). The commands we want you to type look lik e this.

Co de and info rmatio n presented in a gray OBSERVE bo x is fo r yo u to inspect and absorb. This info rmatio n is o ften co lo r-co ded, and fo llo wed by text explaining the co de in detail:

OBSERVE:

Gray "Observe" boxes like this contain information (usually code specifics) for you to observe.

The paragraph(s) that fo llo w may pro vide additio n details o n inf o rm at io n that was highlighted in the Observe bo x.

We'll also set especially pertinent info rmatio n apart in "No te" bo xes:

Note

No tes pro vide info rmatio n that is useful, but no t abso lutely necessary fo r perfo rming the tasks at hand.

T ip

Tips pro vide info rmatio n that might help make the to o ls easier fo r yo u to use, such as sho rtcut keys.

WARNING

Warnings pro vide info rmatio n that can help prevent pro gram crashes and data lo ss.

Understanding the Learning Sandbox Environment

We'll be do ing lo ts o f wo rk in Visual Studio , Micro so ft's Integrated Develo pment Enviro nment (IDE) fo r wo rking with C#. In the next lesso n, we will co ver in-depth ho w to use Visual Studio . Fo r this first lesso n, we'll intro duce yo u to the visual cues to help yo u learn and experiment, and then we'll help yo u create yo ur first C# applicatio n!

(8)

When yo u see this ico n, yo u sho uld save yo ur wo rk. Yo u can save whenever yo u like, and we stro ngly enco urage yo u to get in the habit o f saving yo ur pro jects frequently. Whenever yo u pause to think, let yo ur mo use po inter find o n the To o lbar! It's a great habit to get into !

T he OST Plug-In

We've added a menu item to the Visual Studio system fo r yo ur co nvenience. Use the OST menu to get to yo ur syllabus fo r this co urse at any time. Yo ur menu may have different co urses, o r o nly this co urse, listed.

T ip

This may serve as a "panic butto n," to o ; if yo ur Visual Studio menus start to get co nfusing in the co urse o f yo ur wo rk, yo u can always get back to the default view by selecting this co urse fro m the OST menu.

Let's Do Something!

Okay, eno ugh talk; let's create o ur first C# pro gram! Traditio nally, a first pro gram is o ne that simply displays the text

"Hello , Wo rld!" so we'll walk yo u thro ugh the steps. The go al is to make Studio do so mething NOW! We'll learn mo re abo ut the Studio develo pment enviro nment in the next lesso n. We'll mo ve quickly thro ugh making this first pro gram;

here's an o verview o f the steps:

1. Create a new C# Windo ws Fo rm Applicatio n pro ject called Hello Wo rld.

2. Open and "pin" the To o lbo x.

3. Drag a Label co ntro l fro m the To o lbo x o nto the Windo ws Fo rm.

4. Open the Pro perties Windo w.

5. Set the display Text fo r the Label co ntro l to "Hello , Wo rld!"

6 . Save the Hello Wo rld pro ject.

7. Run the Hello Wo rld pro ject.

Let's get started!

Note

After yo u create the pro ject belo w, yo u wo n't be able to see this lesso n text. To get it back, right-click o n the tab marked Fo rm .cs[De sign] and select Ne w Ho rizo nt al T ab Gro up. This will split the screen with the lesso n page at the to p and the fo rm designer at the bo tto m. Yo u will need to do this each time yo u create a new pro ject. If mo re than o ne pro ject is o pen, yo u can just drag its tab to the lo wer tab gro up to mo ve it.

Creat ing a New Horizont al T ab Group

(9)

When yo u finish, yo u sho uld see so mething like this.

No w, remembering tho se steps, let's create o ur pro ject. Select the File menu, then Ne w, then Pro je ct (in the future, we'll sho w this kind o f menu sequence like this: File | Ne w | Pro je ct ):

(10)

In the New Pro ject dialo g, in the left co lumn, check that Visual C# | Windo ws is selected. In the middle co lumn, make sure Windo ws Fo rm s Applicat io n is selected (these o ptio ns sho uld already be selected by default). At the bo tto m o f the dialo g, in the Name textbo x, replace Windo wsFo rm sApplicat io n1 with He llo Wo rld o r He llo Wo rld (yo u can include spaces in pro ject names to make them mo re readable, if yo u like). Click OK when yo u finish typing the name.

At this po int, yo u'll need to perfo rm the steps described earlier to get the lesso n text back.

No w, we want to have o ur to o ls available all the time, so click T o o lbo x:

(11)

When the To o lbo x expands, click o n the Aut o Hide "pin" ico n at the to p o f the To o lbo x windo w so that the pin is po inting do wn rather than ho rizo ntal. The To o lbo x will no w stay displayed.

(12)

Find the Labe l co ntro l under the Co mmo n Co ntro ls o ptio n.

Click and drag the Labe l o nto the grey area under the bo x named Fo rm1 in the middle o f Visual Studio .

Right-click o n the "label1" text o n Fo rm1, and cho o se Pro pe rt ie s.

(13)

In the Pro perties Windo w at the bo tto m right o f Studio , find the T e xt pro perty in the left co lumn. In the co lumn to the right o f Text, change "label1" to He llo , Wo rld!.

Click Save in the Studio To o lbar (at to p) to save the pro ject.

Find the green St art De bugging butto n in the Studio To o lbar. Click it to run the pro gram!

(14)

Click the small black "x" o r Clo se ico n to clo se yo ur first Windo ws C# applicatio n.

Co ngratulatio ns!!! Yo u've just created and run yo ur first C# applicatio n!!!

Closing and Reopening a Solution

Eventually, o f co urse, yo u will lo ve pro gramming so much yo u'll never want to sto p! Still, yo u might need to take a break fro m time to time, so yo u need to kno w ho w to clo se a so lutio n and to reo pen it when yo u return.

With yo ur Hello Wo rld so lutio n selected in the So lutio n Explo rer, select File | Clo se So lut io n. The So lutio n Explo rer will no w be empty.

To reo pen the so lutio n, select File | Ope n | Pro je ct /So lut io n...

In the dialo g that appears, do uble-click yo ur He llo Wo rld (o r He llo Wo rld) pro ject fo lder, and then select yo ur Hello Wo rld so lutio n.

(15)

Do uble-click Fo rm 1.cs to bring back the fo rm designer (and the to o ls in the To o lbo x).

Studio IDE

So ftware develo pment in .NET uses the Micro so ft Visual Studio Integrated Develo pment Enviro nment (IDE). During this co urse, we will refer to Visual Studio as the Studio IDE, Studio , o r IDE.

An IDE supplies mo st if no t all o f the to o ls yo u will need to develo p so ftware. This lesso n will familiarize yo u with the features o f the Studio IDE, and sho w ho w to use tho se features and co mpo nents to begin creating yo ur o wn so ftware.

A Quick Tour

The Studio IDE initial Start Page lo o ks like this (a po pup dialo g fro m the System Tray may alert yo u to an o ptio nal Custo mer Experience Impro vement Pro gram feature. Yo u may participate o r no t by clicking o n the po pup dialo g):

(16)

The Start Page is a co nvenient presentatio n o f many initial tasks yo u may want to perfo rm when first o pening Studio .

Clo se this page by clicking o n the small x o n the tab labeled Start Page.

T ip

To view the Start Page again at any time, select Vie w | St art Page .

The Studio IDE includes a File menu alo ng the to p o f the applicatio n, butto ns just belo w the menu, and co mpo nents belo w the butto ns. All Studio IDE elements are co ntext sensitive, which means that certain elements may be disabled o r unavailable depending o n what yo u are do ing. Yo u will no tice that many o f the butto ns lo o k dim, o r gray. These butto ns are disabled:

Mo ve yo ur mo use po inter o ver o ne o f the ico ns and pause until a po pup appears; here, fo r example, is the Save All ico n po pup:

(17)

These po pups display the ico n's functio n (and keybo ard sho rtcut, if available). The ico n functio n co rrespo nds to the same functio nality available thro ugh the menu. Fo r example, the Save All functio nality is also available fro m the File menu.

The Studio IDE co ntains many mo re elements than initially appear, and as yo u wo rk mo re with Studio , yo u will learn to add the elements that yo u prefer.

Right-click in the blank area at the to p o f Studio next to the menu items o r butto ns, and select We b Bro wse r. Ico ns appro priate to a web bro wser will no w be visible:

(18)

Note

The Studio IDE co ntains an embedded web bro wser fo r viewing o nline o r o ffline co ntent.

To see the Micro so ft Develo per Netwo rk Fo rums ho me page, click the MSDN Fo rum s ico n:

Yo u will see co ntent similar to this:

(19)

This is a valuable reso urce fo r learning mo re abo ut develo ping so ftware using Visual Studio —we'll visit it again later.

Clo se the Fo rums tab by clicking the in the Visual Studio Catego ry tab header.

T ip

If yo u lo se this lesso n windo w, o r o therwise get co nfused by the rearranging o f windo ws that Visual Studio may do , select OST | Re se t Windo ws fro m the to p menu.

At the to p left co rner o f the Studio windo w, just belo w the ico ns, yo u will see the To o lbo x panel, which we "pinned" in the last lesso n.

If it's no t already o pen, click the wo rd T o o lbo x to expand the butto n into a windo w:

(20)

Yo u'll also see an expanded area to the right o f the Studio windo w labeled So lutio n Explo rer.

Bo th the To o lbo x and So lutio n Explo rer panels co ntain the same three co ntro ls at the to p right: They are labeled Windo w Po sit io n (the arro whead image), Aut o Hide (the pushpin image), and Clo se (the X). Windo w Po sitio n co ntro ls the lo catio n and appearance o f the panel. Auto Hide, if selected (the pushpin being ho rizo ntal) co ntro ls the display o f the panel as yo ur mo use mo ves o ver its ico n. Clo se will clo se and hide the panel.

Click the To o lbo x Windo w Po sit io n and select Flo at :

No w yo u can mo ve the flo ating To o lbo x panel aro und the screen by clicking and dragging it.

T ip

If yo u do uble-click o n the to p o f the panel (the title bar), the panel will maximize. To resto re it to its o riginal size, do uble-click the title bar again.

Click the To o lbo x Windo w Po sit io n butto n again and select Do ck as T abbe d Do cum e nt . No te that the three panel co ntro ls are go ne. To resto re the To o lbo x to flo ating, yo u need to select the Windo w | Flo at menu o ptio n.

To resto re the To o lbo x as a do cked element o n the left o f the screen, select the To o lbo x Windo w Po sit io n butto n again, and select Do ck.

T ip

If yo u clo se o r hide the To o lbo x butto n o r windo w, yo u can unhide it by selecting Vie w | T o o lbo x.

To ggle the Auto Hide pushpin and no te the behavio r when the pushpin is vertical versus when it is ho rizo ntal. When yo u finish, make sure it is vertical so the To o lbo x remains o nscreen.

Creating Your Second Project

Creating so ftware is an interactive pro cess, and experimenting is stro ngly enco uraged! Feel free to experiment mo re with the Studio IDE.

No w that yo u have an idea o f ho w the butto ns wo rk, and ho w to navigate aro und a few o f the Studio elements, let's create ano ther C# pro ject. As we learned in the first lesso n, so ftware develo pers o ften create a simple pro gram that displays the wo rds "Hello Wo rld." Let's create this traditio nal first pro gram again, but with a twist.

Select File | Ne w | Pro je ct . The New Pro ject dialo g presents a rather daunting list o f po ssible pro ject types; just select Windo ws Fo rm s Applicat io n. Then, change the default pro ject name to GraphicalHe llo Wo rld:

(21)

Note

Remember to right-click the Fo rm1.cs tab and select Ne w Ho rizo nt al T ab Gro up so yo u can see this lesso n text again!

Yo u no w see the Studio enviro nment including the GraphicalHello Wo rld pro ject. No te the Fo rm1 fo rm. This fo rm represents the visual element o f the pro gram we will create. A Windo ws Fo rm Applicatio n uses the co ncept o f a rectangular fo rm fo r presenting info rmatio n to the user. Yo u will also no tice that the So lutio n Explo rer no w co ntains info rmatio n.

(22)

The Fo rm1 co mpo nent is a Visual Designer kno wn as the Windo ws Fo rms Designer. Studio co ntains many Visual Designers that we will use thro ugho ut these lesso ns.

The So lutio n Explo rer lists info rmatio n in a hierarchical display related to so lutio ns and pro jects. A pro ject represents a single item, such as the GraphicalHello Wo rld applicatio n, but a so lutio n co ntains o ne o r mo re pro jects. Every pro ject belo ngs to a so lutio n by default. Yo u will use the So lutio n Explo rer to add o r access items within a pro ject o r so lutio n, as well as to co nfigure build settings, publish pro jects and so lutio ns, and perfo rm o ther activities.

Applicatio ns typically co ntain lines o f pro gramming co de that run, o r execute. When yo u run an applicatio n o n yo ur co mputer, yo u are running a published versio n o f that applicatio n. As an applicatio n develo per, yo u can run bo th a published versio n, and a develo pment, o r debug, versio n.

Lo cate the green play butto n labeled St art De bugging. Yo u may also press F5 , o r select De bug | St art De bugging fro m the menu. The same fo rm that yo u saw in Studio appears as a separate windo w:

(23)

Altho ugh this fo rm lo o ks like an independent applicatio n, Studio is still co nnected to it. Yo u can see ho w Studio is still linked to the running GraphicalHello Wo rld applicatio n by the cho ices under the Debug menu.

To sto p running an applicatio n, yo u can either clo se it using the ico n at the to p-right co rner o f the applicatio n, o r yo u can switch back to Studio and click the blue St o p ico n . All o f the Debug co mmands are also available fro m the to p De bug menu.

Click Clo se in the to p-right co rner o f the running GraphicalHello Wo rld applicatio n.

By default, a Windo ws Fo rm Applicatio n is pretty empty. In o ur first C# pro ject, we added the Hello Wo rld text using the To o lbo x. The To o lbo x co ntains co mpo nents we can use in o ur applicatio n. No w we'll add the text again, and then change it to a graphical versio n o f the text. Again, we will first use a label co ntro l.

Do uble-click the Labe l co ntro l in the Co mmo n Co ntro ls o ptio n in the list o f hierarchical gro upings o f the To o lbo x. A new label co ntro l appears o n the fo rm.

(24)

A label co ntro l may be used to display simple text fo r a variety o f reaso ns. A text co ntro l is typically no t a co ntro l that a user can click o n.

Right-click o n the label co ntro l in the fo rm, and select Pro pe rt ie s. No te the appearance o f the Pro perties windo w in the bo tto m right o f Studio (it may already have been visible, as in the image abo ve). Scro ll do wn the left co lumn to the Text pro perty, click o n the field next to the Text pro perty, and type He llo Wo rld to replace the "label1" text. To change the text o f the label co ntro l in the fo rm, yo u can either press Ent e r o r click away fro m the field.

We will learn mo re abo ut the different windo ws co mpo nents o f the To o lbo x later.

No tice in the So lutio n Explo rer that the name o f the Fo rm1 file is Fo rm1.cs. Yo u need to change the name o f Fo rm to so mething meaningful, in this case, GraphicalHello wWo rld.cs. Click o n Fo rm 1.cs to select it in the So lutio n Explo rer.

Once it is selected, the Pro perties windo w will sho w the Fo rm1 pro perties. Change the File Name pro perty fro m Fo rm1.cs to GraphicalHe llo Wo rld.cs and press Ent e r. Yo u may see this dialo g bo x:

This indicates that changing the filename will impact o ther po rtio ns o f yo ur co de, and that Studio can auto matically update all references to the o ld name to the new o ne. This feature o f having the IDE assist yo u when yo u make such changes is kno wn as refacto ring, and we will see mo re refacto ring o ppo rtunities later. Fo r no w, click Ye s to perfo rm the updates.

Press F5 to run the GraphicalHello Wo rld applicatio n and view the Hello Wo rld text (if it do esn't run, click in the Design

(25)

panel area where the fo rm is, and try again). To sto p running the applicatio n, click its Clo se butto n .

T ip

Get in the habit o f saving yo ur wo rk. Often, we will pause while we think abo ut do ing so mething. Train yo urself to click Save o r Save All during these idle times.

Click Save o r Save All, o r press Ct rl+S.

Programming Code

Befo re we can put a bit o f a twist o n the GraphicalHello Wo rld applicatio n, we need to discuss the pro gram co de that makes it wo rk. Studio includes a number o f text o r co de edito rs to make writing yo ur co de a very interactive and efficient pro cess.

Right-click the GraphicalHe llo Wo rld.cs entry in the So lutio n Explo rer and select Vie w Co de (again, yo u'll want to display it in a Ne w Ho rizo nt al T ab Gro up):

Studio adds a new tab to the central windo w sho wing the pro gramming co de, also kno wn as so urce co de, fo r the fo rm. This windo w, sho wn belo w, is a C# Co de Edito r. We will learn mo re abo ut the co de later.

(26)

T ip

To increase the size o f the so urce co de windo w, yo u can hide the To o lbo x windo w by "unpinning" the Auto Hide pushpin.

Mo dify the fo rm co de to lo o k exactly like the co de sho wn belo w (remember: type the highlighted co de yo urself rather than cutting and pasting!). No te the additio n o f the line o f co de belo w InitializeCo mpo nent().

(27)

CODE TO TYPE: GraphicalHello Wo rld using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace GraphicalHelloWorld {

public partial class GraphicalHelloWorld : Form {

public GraphicalHelloWorld() {

InitializeComponent();

// Hide the label to prevent obscuring graphical Hello World this.label1.Visible = false;

}

protected override void OnPaint(PaintEventArgs e) {

// Call the OnPaint method of the base class base.OnPaint(e);

// Call methods of the System.Drawing.Graphics object e.Graphics.DrawString("Graphical Hello World",

new System.Drawing.Font("Arial", 16.0F, FontStyle.Italic), new SolidBrush(ForeColor), 10.0F, 10.0F);

} } }

Note

The "using" sectio n wo n't change much; yo u can co llapse (and thus hide) the sectio n by clicking the minus (-) ico n to the left o f it; to expand and view it again, click the plus (+).

Save yo ur changes, and press F5 to run the mo dified pro gram. No w the "Graphical Hello Wo rld" text in italics is drawn o n the fo rm, rather than using the label co ntro l:

So ho w do es this co de wo rk? Let's OBSERVE and discuss it.

(28)

OBSERVE: GraphicalHello Wo rld Fo rm using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace GraphicalHelloWorld {

public partial class GraphicalHelloWorld : Form {

public GraphicalHelloWorld() {

InitializeComponent();

// Hide the label to prevent obscuring graphical Hello World this.label1.Visible = false;

}

protected override void OnPaint(PaintEventArgs e) {

// Call the OnPaint method of the base class base.OnPaint(e);

// Call methods of the System.Drawing.Graphics object e.Graphics.DrawString("Graphical Hello World",

new System.Drawing.Font("Arial", 16.0F, FontStyle.Italic), new SolidBrush(ForeColor), 10.0F, 10.0F);

} } }

Note

In the OBSERVE bo x, we added co lo r to different elements that we want to fo cus o n. As yo u pro ceed with the lesso ns, yo u'll see this co lo r-co ding to identify different elements in the co de, and to help clarify what is happening.

In the co de abo ve, t his.labe l1.Visible = f alse ; prevents the display o f the Label co ntro l to prevent o bscuring the drawing o f "Hello Wo rld" text. Thro ugho ut the co de, yo u see lines starting with "//." These are single-line co mments, used to help do cument the co de (and igno red at runtime). As yo u learn to pro gram, yo u sho uld add co mments that help yo u and that do cument the functio nality o f yo ur co de.

Add // befo re the t his.labe l1.Visible = f alse ; line and save and rerun the pro gram, then remo ve the // and save and run it again, to see what that line o f co de do es.

The seco nd change to the co de adds an OnPaint metho d that draws the actual "Graphical Hello Wo rld" text o n the Fo rm. We will learn mo re abo ut ho w this co de wo rks later.

Note

When yo u make changes to the co de, Studio highlights these changes with a yello w bar at the left o f the Co de Edito r windo w. Once yo u have saved yo ur changes, the yello w bar changes to green. These

"changed" bars will remain until the file is clo sed.

The Source Code Window

The so urce co de created by Studio , and the co de yo u later typed in, fo llo w very strict rules, o r language semantics. As yo u learn mo re abo ut pro gramming in C#, yo u will learn these rules. The so urce co de windo w includes a number o f helpful features, such as co llapsible so urce co de o utlines sho wn by the gray lines with the minus signs at the left o f the windo w. Yo u can click o n the minus signs to co llapse o ne o r mo re sectio ns o f co de to ease the adding and editing o f o ther co de.

Click o n the minus sign next to the line with the OnPaint text. Click o n the plus sign that appears to redisplay the OnPaint so urce co de.

(29)

The so urce co de edito r also includes an Intellisense feature that assists yo u with the language semantics, pro mpting fo r available elements when co ding, and pro viding a autocompletion feature that, fo r example, adds a clo sing

parenthesis ) when yo u enter an o pening o ne (. We will fo cus mo re o n this and o ther features o f the so urce co de edito r later.

Befo re yo u mo ve o n to the next lesso n, do yo ur ho mewo rk! Right-click in the windo w where this lesso n text appears and select Back. Then, select Quiz fo r this lesso n in the syllabus and answer the quiz questio ns. When yo u finish the quiz questio ns, click Hand it in at the bo tto m o f that windo w. Then do the same with the Pro ject(s) fo r the lesso n. Yo ur instructo r will grade yo ur quiz(zes) and pro ject(s) and pro vide guidance if needed.

No w yo u're ready to mo ve o n where yo u'll dive right in, learning mo re abo ut Visual Studio , and create ano ther C# applicatio n!

Copyright © 1998-2013 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

(30)

Statements, Keywords, Scope, Types, Variables, and Conversions

Introduction to C# Programming and the .NET Framework: Lesson 2

In the first co urse, the emphasis was o n mo ving thro ugh a lo t o f basic material to get up and running quickly. This seco nd co urse will again emphasize hands-on pro gramming, but will be adding mo re depth to yo ur experience with the C# language and the Visual Studio IDE.

In this lesso n, we will learn mo re abo ut the syntax, data types, and variables used with C#.

As with the first co urse, we enco urage yo u to type in all sample co de, as well as experiment o n yo ur o wn!

Programming Statements

Previo usly, we've seen numero us programming statements. Fo r the purpo se o f this co urse, pro gramming statements are like sentences in a spo ken language, co mpo sed o f elements o f the pro gramming language to represent the smallest valid unit. The fo llo wing are examples o f simple pro gramming statements in C#:

Assignm e nt : int myAge = 21;

Me t ho d call: getEmplo yeeName (emplo yeeNumber);

Sim ple branching: break;

Me t ho d re t urn: return myAge;

Yo u can also use co mpo und pro gramming statements:

Branching: if (myAge >= 21) ...

It e rat io n: fo r (int ro wCo unter = 1; ro wCo unter <= to talRo ws; ro wCo unter++) ...

We co nstruct pro gramming statements fro m the building blo cks o f the pro gramming language. These building blo cks co nsist o f reserved keywords (which, as we've mentio ned, may no t be used as identifier names) and identifiers (classes, metho ds, variables) assembled using the C# language syntax.

Identifiers and Reserved Words

The co ncept o f pro gramming statements, identifiers, reserved wo rds, and language syntax sho uld be familiar to yo u fro m the first co urse. Yo u've used quite a few o f the C# reserved wo rds already, such as class, if, else, for, int, string, and so o n. Micro so ft pro vides a co mplete list o f reserved wo rds used with the C# language and Visual Studio 20 10 here:

Visual Studio 20 10 C# Keywo rds

We've defined the rules fo r a C# variable earlier, but we'll repeat tho se rules here as they apply to all identifiers (classes, metho ds, and variables):

Must use o nly letters, digits, o r the undersco re character.

Must> start with a letter o r undersco re.

Is case-sensitive, so radiusOfCircle is NOT the same as RadiusOfCircle.

Must not be a C# keywo rd, such as class, int, etc.

Note

Feel free to investigate so me o f the keywo rds yo u're familiar with, and o thers yo u're no t familiar with.

Also , yo u may no te a seco nd table o f keywo rds referred to as "Co ntextual Keywo rds." We'll discuss these keywo rds later, as we co ver material related to them.

Scope

(31)

Scope Definition

Remember all o f tho se curly braces ({ and }) we used in o ur pro grams? They are part o f an impo rtant co ncept kno wn as scope. Just as we use a micro sco pe to reveal things we may no t be able to see witho ut assistance, programming scope refers to the visibility o f the variables, classes, o bjects, and metho ds thro ugho ut o ur so ftware. Let's create a new pro ject to explo re the co ncepts o f sco pe, including the use o f braces.

Local Scope

Select File | Ne w | Pro je ct . In the New Pro ject dialo g bo x, change the Name o f the pro ject to Sim ple Sco pe , All o ther dro pdo wns and checkbo xes sho uld have their default settings:

Click OK. Yo ur new Windo ws Fo rm Applicatio n appears.

Lo cate and click o n the entry fo r Fo rm 1.cs and replace the highlighted text with Sim ple Sco pe .cs.

Click o n the Fo rm 1 Fo rm title bar, and find the Text pro perty in the Pro perty Windo w. Change the Text pro perty fro m Fo rm1 to Sim ple Sco pe :

(32)

Drag a ListBo x co ntro l fro m the To o lbo x o nto yo ur fo rm, and resize the ListBo x to take up mo st o f the space in the fo rm:

Click the new ListBo x co ntro l, and in the Pro perties Windo w, change the Name pro perty to sco pe List Bo x.

(33)

This is a go o d time to click .

Next, we'll add co de to o ur pro ject, so we'll need to view the Co de Edito r fo r the Fo rm.

Right-click the Sim ple Sco pe .cs Fo rm entry in the So lutio n Explo rer, and select Vie w Co de :

Yo u sho uld see the default Windo ws Fo rm co de fo r yo ur pro ject in the Co de Edito r:

No w, let's add o ur C# co de to explo re the co ncept o f sco pe.

Mo dify the SimpleSco pe.cs co de as sho wn belo w to add the decisio n-making co de:

(34)

SimpleSco pe.cs using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace SimpleScope {

public partial class SimpleScope : Form {

public SimpleScope() {

InitializeComponent();

// Scope variables int numberToSquare = 3;

int squaredResult = 0;

// Call square method and document values.

scopeListBox.Items.Add("Number value BEFORE method call: " + numberT oSquare);

squaredResult = square(numberToSquare);

scopeListBox.Items.Add("Number value AFTER method call: " + numberTo Square);

scopeListBox.Items.Add("Result: " + squaredResult);

}

private int square(int numberToSquare) {

numberToSquare = 5;

return (numberToSquare * numberToSquare);

} } }

and to run the pro gram. Yo u sho uld see this:

As yo u can see, the value o f num be rT o Square remains the same befo re and after the call to the square () metho d, but inside the metho d, the num be rT o Square value assignment wo rked, as the result o f the metho d

(35)

call is the square o f 5, o r 25.

Let's discuss ho w this co de wo rks. As we did in the first co urse, we'll o mit the co de that do esn't co ncern us.

OBSERVE: SimpleSco pe.cs .

. .

public SimpleScope() {

InitializeComponent();

// Scope variables int numberToSquare = 3;

int squaredResult = 0;

// Call square method and document values

scopeListBox.Items.Add("Number value BEFORE method call: " + numberT oSquare);

squaredResult = square(numberToSquare);

scopeListBox.Items.Add("Number value AFTER method call: " + numberTo Square);

scopeListBox.Items.Add("Result: " + squaredResult);

}

private int square(int numberToSquare) {

numberToSquare = 5;

return (numberToSquare * numberToSquare);

} .

. .

Examine the use o f the variable num be rT o Square/num be rT o Square. Yes, they are two different variables. num be rT o Square is used in the SimpleSco pe metho d, and num be rT o Square is a metho d parameter o r argument to the square metho d. Co nsider these questio ns:

Are these two variables really the same variable, perhaps because they bo th have the same name?

Is the value o f num be rT o Square the same before and after the call to square? What happens to num be rT o Square after the call to square?

As yo u co nsider these questio ns, reco gnize that what we're really asking abo ut is scope. Do es a variable declared within o ne metho d beco me the same variable in ano ther metho d if bo th variables have the same name as in o ur co de? The answer is No . The sco pe, o r visibility, o f a variable is determined by where the variable is declared. A variable declared within a metho d is said to have local scope. Once that metho d has been executed, any lo cal variables, including metho d parameters and arguments, no lo nger exist. So what are the answers to the sco pe questio ns?

The two numberTo Square variables are no t the same, as each exists within its o wn lo cal sco pe.

The value o f num be rT o Square remains the same, even if yo u changed num be rT o Square within the square metho d.

Once the square metho d exits, num be rT o Square no lo nger exists.

Block Scope

Within a metho d, yo u can have additio nal levels o f sco pe kno wn as block scope. This level o f sco pe is created whenever yo u use tho se pernicio us {braces}! That means if yo u use C# keywo rds like if(), yo u're creating a blo ck! Let's try that.

Mo dify the SimpleSco pe.cs co de as sho wn belo w.

(36)

SimpleSco pe.cs using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace SimpleScope {

public partial class SimpleScope : Form {

public SimpleScope() {

InitializeComponent();

// Scope variables int numberToSquare = 3;

int squaredResult = 0;

// Call square method and document values

scopeListBox.Items.Add("Number value BEFORE method call: " + numberT oSquare);

squaredResult = square(numberToSquare);

scopeListBox.Items.Add("Number value AFTER method call: " + numberTo Square);

scopeListBox.Items.Add("Result: " + squaredResult);

// Block scope if (1 > 0) {

int firstBlockTest = 10;

}

squaredResult = square(firstBlockTest);

scopeListBox.Items.Add("Result after block: " + squaredResult);

}

private int square(int numberToSquare) {

numberToSquare = 5;

return (numberToSquare * numberToSquare);

} } }

After adding the blo ck co de, yo u'll see a squiggly red erro r line under the firstBlo ckTest variable. If yo u ho ver yo ur mo use po inter o ver the erro r, yo u will see a po pup message that indicates the variable "firstBlo ckTest"

do es no t exist in the current co ntext:

(37)

But we initialized firstBlo ckTest to 10 just a co uple o f lines earlier! What do es this erro r mean? It means that the variable firstBlo ckTest, even tho ugh it was declared within the blo ck if() sco pe, is no lo nger valid because the variable has go ne out of scope. Variables are o ften referred to as in scope o r out of scope, to indicate whether o r no t the variable exists and is visible to the current sco pe. Let's fix the co de so we can use the firstBlo ckTest variable.

Note

Previo usly, we saw that yo u do no t have to use braces with the if() syntax if yo u o nly have a single line, altho ugh we've enco uraged yo u to be co nsistent and include the braces in all cases.

When using a single-line if() blo ck witho ut braces in C#, yo u canno t declare a new variable. Yo u must use braces if yo u want to declare new blo ck-level variables.

Mo dify the Sim ple Sco pe .cs co de as sho wn belo w:

(38)

SimpleSco pe.cs using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace SimpleScope {

public partial class SimpleScope : Form {

public SimpleScope() {

InitializeComponent();

// Scope variables int numberToSquare = 3;

int squaredResult = 0;

// Call square method and document values

scopeListBox.Items.Add("Number value BEFORE method call: " + numberT oSquare);

squaredResult = square(numberToSquare);

scopeListBox.Items.Add("Number value AFTER method call: " + numberTo Square);

scopeListBox.Items.Add("Result: " + squaredResult);

// Block scope

int firstBlockTest = 0;

if (1 > 0) {

int firstBlockTest = 10;

}

squaredResult = square(firstBlockTest);

scopeListBox.Items.Add("Result after block: " + squaredResult);

}

private int square(int numberToSquare) {

return (numberToSquare * numberToSquare);

} } }

and to run the pro gram. Yo u sho uld see this:

(39)

Let's discuss ho w this co de wo rks.

OBSERVE: SimpleSco pe.cs .

. .

// Block scope

int firstBlockTest = 0;

if (1 > 0) {

firstBlockTest = 10;

}

squaredResult = square(firstBlockTest);

scopeListBox.Items.Add("Result after block: " + squaredResult);

. . .

Because the variable f irst Blo ckT e st is no w declared o utside the if blo ck, its sco pe is bro adened; within the braces blo ck, we're simply changing its value. Yo u sho uld no te that yo u may not have a block scope variable with the same name as a local scope variable.

Note

Altho ugh the technique is rarely used, yo u can create a blo ck sco pe simply by using braces! Go ahead, try it!

Class Scope

In previo us lesso ns, we've seen that we can declare variables that serve as pro perties fo r o ur class. These class variables have class scope, and are visible to all o f the metho ds within the class in which they are declared. Unlike with lo cal and blo ck sco pe variables, you are allowed to have a class scope variable with the same name as a local or block scope variable; however, a local or block scope variable takes precedence and will be used over the class scope variable! We'll learn in a later lesso n ho w to select the co rrect variable when a class and lo cal variable have the same name.

Let's add a class-level variable.

Mo dify Sim ple Sco pe .cs as sho wn belo w.

(40)

SimpleSco pe.cs using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace SimpleScope {

public partial class SimpleScope : Form {

private int myClassVariable = 25;

public SimpleScope() {

InitializeComponent();

// Scope variables int numberToSquare = 3;

int squaredResult = 0;

// Call square method and document values

scopeListBox.Items.Add("Number value BEFORE method call: " + numberT oSquare);

squaredResult = square(numberToSquare);

scopeListBox.Items.Add("Number value AFTER method call: " + numberTo Square);

scopeListBox.Items.Add("Result: " + squaredResult);

// Block scope

int firstBlockTest = 0;

if (1 > 0) {

firstBlockTest = 10;

firstBlockTest = 10;

}

squaredResult = square(firstBlockTest);

scopeListBox.Items.Add("Result after block: " + squaredResult);

// Use class scope variable.

scopeListBox.Items.Add("Class variable result: " + square(myClassVar iable));

}

private int square(int numberToSquare) {

return (numberToSquare * numberToSquare);

} } }

and to run the pro gram. Yo u sho uld see this:

(41)

Let's discuss ho w this co de wo rks.

OBSERVE: SimpleSco pe.cs .

. .

namespace SimpleScope {

public partial class SimpleScope : Form {

private int myClassVariable = 25;

public SimpleScope() {

. . .

// Use class scope variable

scopeListBox.Items.Add("Class variable result: " + square(myClassVar iable));

}

private int square(int numberToSquare) {

return (numberToSquare * numberToSquare);

} } . . .

The class variable m yClassVariable is declared o utside o f any metho d, at the class sco pe. We use the variable in o ur call to square and o utput the results. As yo u can see fro m the co de, we did no t need to declare m yClassVariable within the lo cal sco pe to use the variable.

Scope Importance

We've disco vered the differences between lo cal, blo ck, and class sco pe, but why is sco pe so impo rtant? Why no t just declare all variables at the class level? Variables in general are what we use to ho ld info rmatio n as o ur pro grams perfo rm the tasks we've pro grammed THEM to perfo rm, so ensuring o ur variables o nly have the data and values we require is very impo rtant fo r data integrity. As we implement an o bject-o riented appro ach to so ftware develo pment, we want to emplo y the co ncept o f information hiding: limiting access to data and variables to o nly tho se parts o f o ur pro gram, and o ther so ftware, that needs access. Variables require memory, so we sho uld limit class variables to reduce a pro gram's memo ry requirements, and use

(42)

lo cal variables that effectively use memo ry o nly tempo rarily. Finally, declaring and using variables in close proximity to where they are used, such as within a blo ck, makes implementing, understanding, and later deciphering a pro gram a simpler task.

Data Types

Built-In T ypes

We've used a number o f different data types so far, such as bool, int, double, float, long, and string. These are just so me o f the data types available in C#. Here's a co mplete list o f available data types (no te table belo w as well):

Visual Studio 20 10 C# Data Types

As with reserved wo rds, we'll co ntinue to explo re the data types as we wo rk thro ugh these lesso ns, but feel free to click o n any o f the data types and read mo re abo ut what they represent. One co mmo n to pic related to data types is the amo unt o f co mputer memo ry they use, and the ranges o f values they can co ntain. Belo w are all data types, their ranges o f values, the amo unt o f memo ry they use, a reference to the underlying .NET data type, and a co lumn abo ut precisio n, if applicable.

T ype Range Size

.NET Fram e wo rk

T ype

Pre cisio n

bo o l true, false Unsigned 8 -bit

integer System.Bo o lean

sbyte -128 to 127 Signed 8 -bit

integer System.SByte

sho rt -32,76 8 to 32,76 7 Signed 16 -bit

integer System.Int16

int -2,147,48 3,6 48 to 2,147,48 3,6 47 Signed 32-bit

integer System.Int32

lo ng –9 ,223,372,0 36 ,8 54,775,8 0 8 to 9 ,223,372,0 36 ,8 54,775,8 0 7

Signed 6 4-bit

integer System.Int6 4

flo at ±1.5 x 10-45 to ±3.4 x 1038 Signed 32-bit

integer System.Single 7 digits do uble ±5.0 x 10-324 to ±1.7 x 1030 8 Signed 6 4-bit

integer System.Do uble 15-16 digits

decimal (-7.9 x 1028 to 7.9 x 1028) / (100 to 28) Signed 128 -bit

integer System.Decimal

28 -29 significant digits

byte 0 to 255 Unsigned 8 -bit

integer System.Byte

usho rt 0 to 6 5,535 Unsigned 16 -bit

integer System.UInt16

uint 0 to 4,29 4,9 6 7,29 5 Unsigned 32-bit

integer System.UInt32

ulo ng 0 to 18 ,446 ,744,0 73,70 9 ,551,6 15 Unsigned 6 4-bit

integer System.UInt6 4

char U+0 0 0 0 to U+FFFF Unico de 16 -bit

character System.Char

string Character data Operating system

dependant System.String

o bject Object data Operating system

dependent System.Object

Yo u'll no tice that the table co ntains so me familiar data types and unfamiliar data types. There are a number o f integer data types, o r numbers that do no t have any decimal value: sbyte, sho rt, int, and lo ng. There are data types that have decimal places: flo at, do uble, and decimal. There is the familiar bo o lean data type bo o l. There are data types that are like integers, but must be the value 0 o r higher (no n-negative): byte, usho rt, uint, and

(43)

are data types that are like integers, but must be the value 0 o r higher (no n-negative): byte, usho rt, uint, and ulo ng. There is the string data type we've used, and ano ther called char that o nly allo ws a single character.

And, finally, there is the o bject data type, which is the parent data type that all predefined and user-defined data types inherit.

Note

As C# is but o ne pro gramming language suppo rted by the .NET framewo rk, and as with all o ther .NET-based languages, all data types used in C# represent an underlying .NET data type. The .NET Fram e wo rk T ype co lumn indicates the actual underlying .NET data type. They are interchangeable; yo u can use the C# o r the .NET data type in yo ur C# pro grams. Fo r co nsistency, we reco mmend yo u stick with the C# data type names.

Let's experiment mo re with the different data types.

Selecting File | Ne w | Pro je ct . In the New Pro ject dialo g bo x, change the Name to Mo re Variable Fun; all o ther dro pdo wns and checkbo xes sho uld have their default settings. Click OK.

The new Windo ws Fo rm Applicatio n appears.

Lo cate and click the entry fo r Fo rm 1.cs and replace it with Mo re Variable Fun.cs. Click to save yo ur changes.

Next, let's add an sbyte and SByte to o ur co de, and see what Intellisense tells us abo ut this smallest o f integer data types.

Mo dify Mo re Variable Fun.cs as sho wn belo w:

(44)

Mo reVariableFun.cs using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace MoreVariableFun {

public partial class MoreVariableFun : Form {

public MoreVariableFun() {

InitializeComponent();

// Fun with integers.

sbyte firstVariable = 1;

SByte secondVariable = firstVariable;

} } }

As we mentio ned, sbyte and SByte (System.SByte) are syno nymo us in C#. Yo u sho uld use the C# sbyte data type rather than the .NET underlying variable data type, but this example illustrates that yo u can use them interchangeably. The co de also illustrates that—as yo u wo uld expect with co mpatible data types—yo u can assign the value o f o ne variable, f irst Variable, to ano ther o f the same data type, se co ndVariable.

Mo reVariableFun.cs .

. .

InitializeComponent();

// Fun with integers.

sbyte firstVariable = 1;

SByte secondVariable = firstVariable;

. . .

Further, if yo u ho ver yo ur mo use po inter o ver either sbyt e o r SByt e, yo u'll see the same Intellisense po pup:

Two key differences with numeric data types are the range o f the data type, and the amo unt o f memo ry needed to ho ld a variable declared as that specific data type. Yo u must be aware o f the data type range, o r yo u will experience what is kno wn as overflow, which means yo u have attempted to sto re a number that exceeds the capacity o f the data type yo u've cho sen—much like po uring 14 o unces o f water into a 12-o unce co ntainer.

Let's see what happens if we try to set o ne o f the variables to a value larger than it can ho ld. Fo r sbyte, acco rding to o ur table, the range is -127 to 127.

(45)

Mo dify Mo re Variable Fun.cs as sho wn:

Note

Remember, yo u can hide o r display different sectio ns o f yo ur so urce co de to make it easier to view using the plus o r minus symbo l that appears to the left o f the first line in the sectio n. Here, we're hiding the using sectio n.

Mo reVariableFun.cs using ...

namespace MoreVariableFun {

public partial class MoreVariableFun : Form {

public MoreVariableFun() {

InitializeComponent();

// Fun with integers.

sbyte firstVariable = 1128;

SByte secondVariable = firstVariable;

} } }

As so o n as yo u change the assignment fro m 1 to 128 , yo u will see the red squiggly erro r line under the 128 . Ho ver yo ur mo use po inter o ver the 128 and no te the po pup erro r bo x indicating that yo u can't assign 128 to sbyte, which is what yo u'd expect fro m the range o f values fo r an sbyte fro m the table:

Note

Yo u might think that yo u sho uld try to use the smallest po ssible data type based o n the range o f the number yo u might use, but in general, when declaring metho d level variables, yo u sho uld use data types that are divisible by 32, as these numbers sto re mo re efficiently in memo ry, and pro cess faster thro ugh the co mputer pro cesso r. So , fo r an integer, yo u sho uld use int o r lo ng.

Fo r numbers with decimal places, yo u can use flo at, altho ugh the default numeric value in C# is do uble, so using do uble data types is mo re co mmo n.

Let's change the co de again to allo w this larger value by using integer data types that allo w a much larger range o f values. Fro m o ur table, the next larger integer data type is sho rt, then int, and, finally, lo ng.

Mo dify Mo re Variable Fun.cs as sho wn belo w.

(46)

Mo reVariableFun.cs using ...

namespace MoreVariableFun {

public partial class MoreVariableFun : Form {

public MoreVariableFun() {

InitializeComponent();

// Fun with integers.

sbyteshort firstVariable = 128;

SByteint secondVariable = firstVariable;

} } }

Remember to perio dically!

As yo u can see, we changed the sbyte to sho rt, and SByte to int. Remember, yo u can almo st always assign numeric data o f a smaller data type to variables o f a larger data type. This pro cess is called widening, which we've discussed befo re, and is always po ssible when the resulting assignment will no t result in a lo ss o f data. In fact, the sho rt data type is promoted using implicit casting during the assignment fro m a sho rt to an int.

C# uses implicit casting whenever necessary to allo w assignment where no data lo ss will o ccur. In instances where implicit co nversio n is no t allo wed, Visual Studio will indicate that fact with an erro r.

Note

What do es signed and unsigned mean? We've previo usly indicated that unsigned means the data type can o nly sto re values that are greater than o r equal to 0 , but fro m a memo ry po int o f view, yo u'll no tice that unsigned data types have a slightly larger range than their equivalent signed data types. The reaso n is that unsigned data types do no t have to sto re the sign, and have mo re sto rage space to increase their range. The same reco mmendatio n applies when using unsigned data types: use a data type that is divisible by 32.

In o ur table, fo r flo at, do uble, and decimal types, the Precisio n co lumn indicates an impo rtant po int abo ut numbers with decimal places, also kno wn as precision. These three data types are no t identical. Flo at and do uble are bo th floating-point data types, which means that as the number gets larger, the decimal po int flo ats, and the large number is represented using scientific, o r expo nential, no tatio n. Fo r mo st calculatio ns, using a flo ating po int data type is sufficient, but if yo u need to co ntro l the precisio n mo re precisely, fo r example with scientific calculatio ns o r currency, yo u sho uld use decimal. The signif icant digit s refers to precisio n, which can be fixed and maintained in decimal, but may be lo st in the flo ating po int data types.

Let's wo rk with these data types as well.

Mo dify Mo re Variable Fun.cs as sho wn belo w.

(47)

Mo reVariableFun.cs using ...

namespace MoreVariableFun {

public partial class MoreVariableFun : Form {

public MoreVariableFun() {

InitializeComponent();

// Fun with integers.

short firstVariable = 128;

int secondVariable = firstVariable;

// Fun with float, double, and decimal.

float thirdVariable = 0.0;

double fourthVariable = thirdVariable;

decimal fifthVariable = fourthVariable;

} } }

Mo re squiggly red line erro rs!

Ho ver o ver the squiggly red erro r line under the 0 .0 assignment, and examine the erro r message.

Yo u might remember that numeric literals in C#, by default, are do ubles. Attempting to assign a do uble to a flo at co uld result in data lo ss, so Visual Studio will no t allo w it. The erro r message gives yo u a hint o n ho w to fix the pro blem: add an F after the numeric literal 0 .0 to change it fro m a do uble to a flo at.

Mo dify Mo re Variable Fun.cs as sho wn belo w:

(48)

Mo reVariableFun.cs using ...

namespace MoreVariableFun {

public partial class MoreVariableFun : Form {

public MoreVariableFun() {

InitializeComponent();

// Fun with integers.

short firstVariable = 128;

int secondVariable = firstVariable;

// Fun with float, double, and decimal.

float thirdVariable = 0.00.0F;

double fourthVariable = thirdVariable;

decimal fifthVariable = fourthVariable;

} } }

Ho ver o ver the squiggly red erro r line under the fo urthVariable variable and examine the erro r message:

This message might be puzzling—why can't a do uble be co nverted to a decimal? If we examine the table, yo u'll no te that even tho ugh a decimal can ho ld a much larger range o f decimal places, the range o f values is much smaller, so Visual Studio do esn't allo w yo u to implicitly cast fro m do uble to decimal. In fact, yo u also can't reverse the pro cess and implicitly cast fro m decimal to do uble, as that co nversio n co uld result in a lo ss o f precisio n. So , what can we do ? The erro r message again indicates a po ssible so lutio n by stating that an explicit co nversio n exists.

Mo dify Mo re Variable Fun.cs as sho wn belo w.

Mo reVariableFun.cs using ...

namespace MoreVariableFun {

public partial class MoreVariableFun : Form {

public MoreVariableFun() {

InitializeComponent();

// Fun with integers.

short firstVariable = 128;

int secondVariable = firstVariable;

// Fun with float, double, and decimal.

float thirdVariable = 0.0F;

double fourthVariable = thirdVariable;

decimal fifthVariable = Convert.ToDecimal(fourthVariable);

} } }

(49)

That fixed the pro blem, and sho wed us a handy o bject we can use fo r co nversio n between different data types: Convert. As yo u type in Co nve rt , then type the perio d, yo u'll no tice the Intellisense dro pdo wn pro viding an extensive list o f co nversio n o ptio ns:

Yo u can use the Co nvert o bject fo r mo st o f yo ur co nversio n needs, and yo u'll see it used by many C#

so ftware develo pers, but, there is o ne slight pro blem with this o bject. What will happen if yo u attempt to do a co nversio n, but the co nversio n fails? Let's further mo dify o ur co de to create a failed Co nvert scenario using the Co nvert.To Int32() co nversio n to co nvert a string literal to an int.

Mo dify Mo re Variable Fun.cs as sho wn belo w.

Mo reVariableFun.cs using ...

namespace MoreVariableFun {

public partial class MoreVariableFun : Form {

public MoreVariableFun() {

InitializeComponent();

// Fun with integers.

short firstVariable = 128;

int secondVariable = firstVariable;

// Fun with float, double, and decimal.

float thirdVariable = 0.0F;

double fourthVariable = thirdVariable;

decimal fifthVariable = Convert.ToDecimal(fourthVariable);

// Create a failed Convert scenario.

int seventhValue = Convert.ToInt32("1.23456");

} } }

Save yo ur changes, and click to execute the pro gram. An erro r, o r exception, o ccurs:

References

Related documents

This need is recognized by the Department of Science and Technology, Government of India and it has initiated to support Institutions to train faculty members of Engineering

Just as it is not necessary for the system to preserve sharing, the system need not help the programmer in transmitting cyclic values. In this case the program- mer

array_name is the name of the array — any valid identifier CAPACITY (a positive integer constant) is the number of elements.. in

Reference Types And Value Types In C C Sharp Reference Types This tutorial will cover somewhat different types available release the C Programming language In C.. In last case to

When u32 and friends were introduced in Version 1.1.67, the developers couldn’t change existing data structures to the new types because the compiler issues a warning when there is

If you are involved in the care of stroke patients—whether you are an advanced practice nurse, stroke coordinator or administrator, critical care neuroscience nurse, preparing

How data types used most basic for us improve user uses different variables that storage space tell excel basics for additional analysis to the..

Defines a structure that contains the function pointers used to configure behavior of NSHashTable with respect to elements within a hash table.. typedef