Chapter 3
Variables,
Constants, and
Calculations
Programming in C# .NET
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Objectives
• Distinguish between variables, constants, and
controls
• Differentiate among the various data types
• Apply naming conventions incorporating
standards and indicating scope and data type
• Declare variables and constants
• Select the appropriate scope for a variable
• Convert text input to numeric values
3- 2
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Objectives cont.
• Perform calculations using variables and constants
• Round decimal values using the decimal.Round
method
• Format values for output using the ToString method
• Use try/catch blocks or error handling
• Display message boxes with error messages
• Accumulate sums and generate counts
3- 3
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Data – Variables and Constants
• C# allows you to set up locations in
memory and give each location a name
• Variables – Memory locations that hold
data that can be changed during project
execution
• Constants – Memory locations that hold
data that cannot be changed during project
execution
3- 4
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Data – Variables and Constants
cont.
• Variables and named constants are given a name,
called an identifier
• Declaration statements are used to create
variables and constants, give them names and
specify their data type
• Examples:
string strName;
//Declare a string variable
int intCounter;
//Declare an integer variable
const float fltDISCOUNT_RATE = 0.15f;
//Declare a named constant
3- 5
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Data Types
• The data type indicates what type of information
will be stored for a variable or constant
• Most common types used are string, int, and
decimal
• If data will be used in a calculation, it must be
numeric
• If data not used in a calculation, it will be a string
• Use decimal for any decimal fractions
3- 6
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
C# Data Types
•
•
•
•
•
•
3- 7
bool
byte
char
DateTime
decimal
float
•
•
•
•
•
•
double
short
int
long
string
object
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Identifier Naming Rules
• Identifiers created in C# must follow these
rules:
–
–
–
–
May consist of letters, digits, and underscores
Must begin with a letter or underscore
Cannot contain any spaces or periods
May not be reserved words
• Names in C# are case sensitive
3- 8
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Identifier Naming Conventions
• Identifiers created in C# should follow these
guidelines:
– Identifiers must be meaningful
– Precede each identifier with a lowercase prefix
that specifies the data type
– Capitalize each word of the name (following
the prefix); Always use mixed case for
variables and uppercase for constants
3- 9
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Common Data Types and
Prefixes
Prefix
Data Type
Description
bln
bool
boolean
dat
DateTime
date and time
dec
decimal
decimal
dbl
double
double-precision floating point
int
int
integer
lng
long
long integer
flt
float
single-precision floating point
str
string
string
3- 10
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Constants – Named and Intrinsic
• Intrinsic constants – Constants built into
the Visual Studio .NET environment
• Named constants – Constants you define
for yourself in the program
3- 11
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Named Constants
• Declare named constants using keyword const
• Give each constant a name, a data type, and a
value
• Value of a constant cannot be changed during
execution of the project
• Named constants make code easier to read
• Later changes to the value of a constant are
made in only one place in code
3- 12
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Named Constants cont.
• General form
const Datatype Identifier = Value;
• Use all uppercase for name of constant with
words separated by underscores
• Examples:
const string strCOMPANY_ADDRESS = “101 S. Main Street”;
const decimal decSALES_TAX_RATE = .08M;
3- 13
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Assigning Values to Constants
• Rules for assigning values to constants
– Test (string) values must be in quotation marks
– Numeric values are not in quotation marks
– Numeric values contain only digits (0-9), a
decimal point, and a sign (+ or -) at the left side
– Numeric values cannot include a comma, dollar
sign, any special characters, or a sign at the
right side
3- 14
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Assigning Values to Constants
cont.
• Type-declaration characters are used to
declare data type of numeric constants
• Type-declaration characters
–
–
–
–
–
3- 15
decimal
double
int
long
float
M or m
D or d
I or i
L or l
F or f
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Assigning Values to Constants
cont.
• Precede a quotation mark that is part of a string with
a backslash (\)
• Example: “He said, \”I like it. \””
produces this string
He said, “I like it.”
• Precede a backslash that is part of a string with
another backslash
• Example:
string strFilePath= “C:\\MyPersonalDocuments\MyLetter”;
• String values are referred to as string literals
3- 16
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Intrinsic Constants
• Intrinsic constants are system-defined
constants
• Declared in system class libraries
• Must specify class name or group name to
use an intrinsic constant
• In Color.Red, “Red” is the constant and
“Color” is the class
3- 17
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Declaring Variables
• Declare a variable by specifying the data
type followed by an identifier
• General Forms:
Datatype Identifier;
Datatype Identifier = LiteralOfCorrectType;
• Examples:
string strCustomerName;
string strCustomerName = “None”;
3- 18
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Declaring Variables cont.
• You can declare several variables in one
statement
• Separate the variable names with commas
and place a semicolon at end of statement
• Examples:
string strName, strAddress, strPhone;
int intCount = 0, intTotal = 0;
3- 19
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Initializing Numeric Variables
• Numeric variables must be assigned a value
before they can be used
• Initialize a variable when you declare it
int intQuantity = 0;
• Declare variable and assign value later
int intQuantity;
intQuantity = int.Parse(quantityTextBox.Text);
• Declare and initialize with expression
int intQuantity = int.Parse(quantityTextBox.Text);
3- 20
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Scope and Lifetime of Variables
• Scope is the visibility of a variable
• Scope levels
–
–
–
–
Namespace
Class
Local
Block
• Scope is determined by where the variable
is declared
3- 21
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Scope and Lifetime of Variables
cont.
• Lifetime of a variable is the period of time
that the variable exists
• Lifetime of a local or block-level variable is
one execution of a method
• Lifetime of a class-level variable is the
entire time the class is loaded
3- 22
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Local Declarations
• Any variable declared inside a method is
local in scope
• A declaration can appear anywhere in the
method but top of the method is preferable
• Constants can also be local, block, class or
namespace level
• Constants are typically declared at the class
level
3- 23
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Class-Level Declarations
• Variables or constants declared as class-level are
used anywhere in the form’s class
• Place class-level declarations at top of the class,
outside of any methods
• Class-level variables initialize automatically when
the class is instantiated
• Numeric variables initialize to zero, string
variables to null, and boolean variables to false
3- 24
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Locations for Coding Variables
and Constants
namespace MyProjectNamespace
{
public class frmMainForm : …
{
declare ModuleLevelVariables
const NamedConstants
private void calculateButton_Click (…)
{
declare LocalVariables
…
{
declare BlockLevelVariables
}
}
}
}
3- 25
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Coding Class, Block, and
Namespace-Level Declarations
• Class-level variables must be inside a class
but not inside a method
• Block-level variables and constants have a
scope of a block of code
• Namespace-level variables and constants
are used when a project has multiple forms
and/or other classes
3- 26
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Calculations
• In programming, calculations can be
performed with variables, constants, and
with the properties of certain objects
• Some character strings must be converted to
a different data type before they can be used
in calculations
3- 27
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Converting Strings to a Numeric
Data Type
• Use the Parse method to convert the Text property
of a control to its numeric form
• Each data type has its own Parse method
• Example:
intQuantity = int.Parse(quantityTextBox.Text);
• Casting is the conversion of one data type to
another
• Parsing means to pick apart a value, character by
character, and convert it to another format
3- 28
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Arithmetic Operations
• C# arithmetic operations
–
–
–
–
–
Addition
Subtraction
Multiplication
Division
Modulus
• Modulus returns the remainder of a division
operation
• Use the pow method to perform exponentiation
3- 29
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Arithmetic Operators
3- 30
Operator
Operation
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus – Remainder of division
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Order of Operations
•
The order in which operations are performed
determines the result
Order of precedence
•
1.
2.
3.
4.
3- 31
Any operation inside parentheses
Multiplication and division
Modulus
Addition and subtraction
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Order of Operations cont.
• Use parenthesis to change the order of
evaluation
• Parenthesis can be nested inside one another
• Extra parenthesis can be used for clarity
• Multiple operations at same level are
performed from left to right
• Example:
8/4*2=4
3- 32
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Order of Operations cont.
•
Order of evaluation of expressions
1. All operations within parentheses. Multiple operations
within the parentheses performed according to rules of
precedence.
2. All multiplication and division. Multiple operations are
performed from left to right.
3. Modulus operations. Multiple operations are
performed from left to right.
4. All addition and subtraction are performed left to right.
•
3- 33
There are no implied operations in C#
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Using Calculations in Code
• You can perform calculations in assignment
statements
• These assignment operators perform a calculation
and assign the result in one operation
+= -= *= /= %=
• Example:
decTotalSales += decSales;
is the same as
decTotalSales = decTotalSales + decSales;
3- 34
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Increment and Decrement
Operators
• Increment operator (++) adds 1 to a variable
• Example: intCount++;
• Decrement operator (--) subtracts 1 from the
variable
• Example: intCountDown--;
• A prefix operator is placed before the
variable
• A postfix operator is placed after the variable
3- 35
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Converting between Numeric
Data Types
• Conversion from a narrower data type to a
wider data type is implicit conversion
• Example: double dblBigNumber = intNumber;
3- 36
From
To
byte
short, int, long, float, double, or decimal
short
int, long, float, double, or decimal
int
long, float, double, or decimal
long
float, double, or decimal
float
double
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Converting between Numeric
Data Types cont.
• Explicit conversion also known as casting
• Exception is generated if significant digits
are lost when a cast is performed
• To cast, specify destination data type in
parenthesis before value to convert
• Examples:
decNumber = (decimal) fltNumber;
intValue = (int) dblValue;
3- 37
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Calculations with Unlike Data
Types
•
•
C# performs calculation with the wider
data type if data types are unlike
Example:
intCount / 2 * decAmount
1. intCount / 2 is integer division producing an integer result
2. Multiplication performed with the integer result and
decimal value (decAmount) producing a decimal result
3- 38
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Rounding Numbers
• Use the decimal.Round method to round decimal
values to the desired number of decimal
positions
• General form
Decimal.Round(DecimalValue, IntegerNumberOfDecimalPositions)
• Example:
decResult = decimal.Round(decAmount, 2);
• decimal.Round
3- 39
uses “rounding toward even”
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Formatting Data for Display
• Numeric data displayed in Text property
must be converted to a string
• Can format data for display
• Use ToString method and formatting codes
• Use ToString with empty argument list to
return an unformatted string
• Example:
displayLabel.Text = intNumber.ToString();
3- 40
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Using Format Specifier Codes
• Use format specifier codes with ToString to format
output display
• “C” code specifies currency
• Example:
extendedPriceLabel.Text = (intQuantity * decPrice).ToString(“C”);
• “N” code specifies number
• Example:
discountLabel.Text = decDiscount.ToString(“N”);
• Specify number of decimal positions with a digit
following the code
3- 41
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Using Format Specifier Codes
cont.
• Formatted value returned by ToString method
is not purely numeric and cannot be used in
calculations
• Format DateTime values using format codes
and the ToString method
• Date codes are case sensitive unlike
numeric format codes
3- 42
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Format Specifier Codes
Format
Name
Specifier
Code
Description
C or c
Currency
Formats with dollar sign, commas, and 2 decimal places.
Negative values are in parentheses.
F or f
Fixed-point Formats as string of numeric digits, no commas, 2 decimal
places, and minus sign at left if negative.
N or n
Number
Formats with commas, 2 decimal places, and a minus sign at
the left for negative values.
D or d
Digits
Use only for integer data types. Minus sign at left for negative
values. Forces number of digits to display.
P or p
Percent
Multiples value by 100, adds space and percent sign, rounds to
2 decimals; minus sign at left if negative.
3- 43
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
A Calculation Programming
Example
R ‘n R – For Reading ‘n Refreshment –
needs to calculate prices and discounts for
books sold. The company is currently
having a big sale, offering a 15 percent
discount on all books. In this project, you
will calculate the amount due for a quantity
of books, determine the 15 percent discount,
and deduct the discount, giving the new
amount due – the discounted amount.
3- 44
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Handling Exceptions
• Processing with invalid input or failed
methods can cause an exception to occur
(also called throwing an exception)
• “Catching” exceptions before they cause a
run time error is called error trapping
• Coding to take care of problems is called
error handling
3- 45
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
try / catch Blocks
• Enclose statement(s) that might cause an
error in a try / catch block
• If an exception occurs in try block, program
control transfers to the catch block
• Code in a finally statement is executed last
• Specify type of exception to catch and
program several catch statements
3- 46
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
The try Block – General Form
try
{
// statements that may cause error
{
catch [(ExceptionType VariableName)]
{
// statements for action when exception occurs
}
[finally
{ // statements that always execute before exit of try
block
}
}
}]
3- 47
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
The Exception Class
• Each exception is an instance of the
Exception class
• Properties of the Exception class
– Message property – Contains a text message
about the error
– Source property – Contains the name of the
object causing the error
– StackTrace property – Identifies the location in
the code where the error occurred
3- 48
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Handling Multiple Exceptions
• Include multiple catch blocks (handlers) to
trap for more than one exception
• Catch statements are checked in sequence
• The last catch can be coded to handle any
exceptions not previously caught
• A compiler warning is generated if a
variable is declared but not used in a catch
block
3- 49
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Displaying Messages in
Message Boxes
• Use Show method of the MessageBox object
• Show method arguments must match one of
the following formats
MessageBox.Show(TextMessage);
MessageBox.Show(TextMessage, TitlebarText);
MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons);
MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons,
MessageBoxIcon);
3- 50
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Displaying Messages in
Message Boxes cont.
• TextMessage
– Message to appear in the message box
– May be a string literal in quotes or a string variable
• TitleBarText
– Appears on the title bar of the MessageBox window
• MessageBoxButtons
– Specifies the buttons to display
– Choices are OK, OKCancel, RetryCancel, YesNo,
YesNoCancel, and AbortRetryIgnore
3- 51
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Displaying Messages in
Message Boxes cont.
• MessageBoxIcon
– Determines the icon to display
– Constants for MessageBoxIcon
•
•
•
•
•
•
•
•
•
3- 52
Asterisk
Error
Exclamation
Hand
Information
None
Question
Stop
Warning
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
MessageBox Statement
Examples
MessageBox.Show(“Enter numeric data.”);
MessageBox.Show(“Try again.”, “Data Entry Error”);
MessageBox.Show(“This is a message.”, “This is a title bar”,
MessageBoxButtons.OK);
try
{
intQuantity = int.Parse(quantityTextBox.Text);
quantityLabel.Text = intQuantity.ToString();
}
catch
{
MesageBox.Show(“Nonnumeric Data.”, “Error”,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
3- 53
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Using Overloaded Methods
• Overloading allows a method to act
differently for different arguments
• Each argument list is called a signature
• Visual Studio .NET editor IntelliSense
popup helps you enter the arguments
correctly
3- 54
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Testing Multiple Fields
• A nested try/catch block is one try/catch
block completely contained inside another
• Nest the try/catch blocks as deeply as
needed
• Place calculations within the most deeply
nested try
3- 55
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Counting and Accumulating
Sums
• Summing numbers
– Declare variable as class level to hold the total
– Example: decPriceSum += decPrice;
• Counting
– Declare variable as class level integer to hold count
– Example: intSaleCount ++;
• Calculating an average
– Divide the sum of numbers by the count
– Example: decAverageSale = decPriceSum / intSaleCount;
3- 56
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Your Hands-On Programming
Example
In this project, R ‘n R – For Reading ‘n
Refreshment needs to expand its book sale
project done previously in this chapter. In
addition to calculating individual sales and
discounts, management wants to know the
total number of books sold, the total number
of discounts given, the total discounted
amount, and the average discount per sale.
3- 57
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Your Hands-On Programming
Example cont.
Help the user by adding ToolTips
wherever you think them useful.
Add error handling to the program so
that missing or nonnumeric data will not
cause a run-time error.
3- 58
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Summary
• Variables are temporary memory locations that have
a name, data type, and scope. Constants also have a
name, data type, scope, and value assigned that
cannot change.
• Data type determines the type of values that can be
assigned to a variable or constant.
• Identifiers for variables and constants must follow
C# naming rules and should following conventions.
• Intrinsic constants are predefined and built into the
.NET Framework. Named constants are
programmer-defined.
3- 59
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Summary cont.
• Variables are declared by indicating the data type
and identifier. Location of declaration determines
the scope.
• The scope of a variable may be namespace level,
class level, local or block level.
• The lifetime of a local and block-level variables is
one execution of the methods where they were
declared. The lifetime of a class-level variable is
the length of time the class is loaded.
3- 60
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Summary cont.
• Identifiers should include a prefix defining the
data type of the variable or constant.
• Use the Parse methods to convert text values to
numeric before performing calculations.
• Calculations are performed using numeric
variables, constants, and properties of controls.
Result is assigned to a numeric variable or the
property of a control.
• Calculations with more than one operator follow
the order of precedence. Parentheses may alter the
order of operations.
3- 61
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Summary cont.
• The decimal.Round method rounds a decimal value
to the specified number of decimal positions.
• The ToString method is used to specify the
appearance of values for display.
• try/catch/finally statements used to check for user
errors
• An error is called an exception. Catching and
taking care of exceptions is error trapping and
error handling.
3- 62
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Summary cont.
• Trap for different types of errors by specifying the
exception type on the catch statement.
• A message box is used to display information to
the user.
• The Show method of the MessageBox class is
overloaded.
• Calculate sums and counts by adding class-level
variables for calculations.
3- 63
© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.