32
Lesson 02 Working with Data Types MIT 31043: RAPID APPLICATION DEVELOPMENT By: S. Sabraz Nawaz Senior Lecturer in MIT

Lesson 02 Working with Data Types - sabraz | Just … 02 Working with Data Types MIT 31043: RAPID APPLICATION DEVELOPMENT By: S. Sabraz Nawaz Senior Lecturer in MIT Variables • A

Embed Size (px)

Citation preview

Lesson 02

Working with

Data TypesMIT 31043: RAPID APPLICATION DEVELOPMENT

By: S. Sabraz Nawaz

Senior Lecturer in MIT

Variables

• A variable is a storage location in memory that is represented by a name. A variable stores data, which are processed with statements. A program is a list of statements that manipulate variables. To write even simple applications, you need a basic understanding of some fundamental topics, such as the data types (the kind of data you can store in a variable), the scope and lifetime of variables, and how to write procedures and pass arguments to them.

• A variable has a name and a value. The variable UserName, for example, can have the value SaNa, and the variable Salary can have the value 10000. UserName and Salary are variable names, and SaNa and 10000 are their values. SaNa is a string (that is, text or an alphanumeric value), and 10000 is a numeric value. When a variable’s value is a string, it must be enclosed in double quotes. In your code, you can refer to the value of a variable by the variable’s name.

• In addition to a name and a value, variables have a data type, which determines what kind of values we can store to a variable. C# supports several data types. The data type of a variable is specified when the variable is declared, and you should always declare variables before using them.

Slide 2

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Naming variables• You should adopt a naming convention for variables that helps you to avoid

confusion concerning the variables you have defined. This is especially

important if you are part of a project team with several developers working

on different parts of an application; a consistent naming convention helps

to avoid confusion and can reduce the scope for bugs.

• The following list contains some general recommendations:

o In a multiword identifier, start the second and each subsequent word with an

uppercase letter. (This is called camelCase notation.)

o Don’t start an identifier with an underscore

o Don’t create identifiers that differ only by case.

• For example, myVariable and MyVariable

o Start the name with a lowercase letter.

Slide 3

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Data Types: Integer Types

TYPE .NET Type ALLOWED VALUES

sbyte SByte Integer between −128 and 127

byte Byte Integer between 0 and 255

short Int16 Integer between −32768 and 32767

ushort UInt16 Integer between 0 and 65535

int Int32 Integer between −2147483648 and 2147483647

uint UInt32 Integer between 0 and 4294967295

long Int64 Integer between −9223372036854775808 and

9223372036854775807

ulong UInt64 Integer between 0 and 18446744073709551615

The u characters before some variable names are shorthand for unsigned, meaning that

you can’t store negative numbers in variables of those types, as shown in the Allowed

Values column of the preceding table.

Slide 4

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Data Types: Floating-point Types

TYPE .NET TypeAPPROX MIN VALUE

APPROX MAX VALUE

float Single 1.5 × 10−45 3.4 × 1038

double Double 5.0 × 10−324 1.7 × 10308

decimal Decimal 1.0 × 10−28 7.9 × 1028

Slide 5

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Data Types: Text and Boolean Types

TYPE .NET Type ALLOWED VALUES

char Char Single Unicode character, stored as an integer

between 0 and 65535 string String A sequence of characters

bool Boolean Boolean value, true or false

Slide 6

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Declaring variables• In most programming languages, variables must be declared in advance.

Historically, the reason for doing this has been to help the compiler

generate the most efficient code. If the compiler knows all the variables and

their types ahead of time, it can produce the most compact and efficient, or

optimized, code.

• You declare the type and name of a variable in a declaration statement.

• The variable type int is the name of one of the primitive C# types, integer,

which is a whole number.

• After declaring, you can assign it a value.

age = 35;

int age;

Slide 7

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Syntax

type variableName = value;

Examples

int intCounter = 1;

long lngNumberOfBytes = 20000;

float fltInterestRate = 8.125f;

// f or F indicates a float value

double dblPrice = 14.95;

decimal decTotal = 24218.1928m;

// m or M indicates a decimal value

char chrLetter = 'A';

// enclose a character value in single quotes

bool blnValid = false;

int intX = 0, intY = 0;

// initialize 2 variables with 1 statement

Declaring variables…

Slide 8

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Named Constant

• A named constant is a name that represents a value that cannot

be changed during the program’s execution.

• Assume that the following statement appears in a banking

program that calculates data pertaining to loans:

o amount = balance * 0.069;

• Two potential problems arise:

o First, it is not clear to anyone other than the original programmer what

0.069 is.

o The second problem occurs if this number is used in other calculations

throughout the program and must be changed periodically.

Slide 9MIT 31043 RAPID APPLICATION DEVELOPMENT

How to declare and initialize a constant

Syntax

const type CONSTANT_NAME = value;

Examples

const int DAYS_IN_NOVEMBER = 30;

const decimal SALES_TAX = .075m;

Naming conventions

Capitalize all letters for each word of a constant name, separating

with underscores.

Declaring Constants

Slide 10

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Operator Name Description

+ Addition Adds two operands.

- Subtraction Subtracts the right operand from

the left operand.

* Multiplication Multiplies the right operand and the

left operand.

/ Division Divides the right operand into the

left operand. If both operands are

integers, then the result is an

integer.

% Modulus Returns the value that is left over

after dividing the right operand into

the left operand.

Arithmetic Operators

Slide 11

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Operator Name

= Assignment

+= Addition

-= Subtraction

*= Multiplication

/= Division

%= Modulus

Arithmetic operators (continued)

Operator Name Description

+ Positive sign Returns the value of the operand.

- Negative sign Changes a positive value to

negative, and vice versa.

++ Increment Adds 1 to the operand (x = x + 1).

-- Decrement Subtracts 1 from the operand

(x = x - 1).

Slide

12

By: S. Sabraz Nawaz

Assignment Operators

MIT 31043 RAPID APPLICATION DEVELOPMENT

The syntax for a simple assignment statement variableName = expression;

Typical assignment statements intCounter = 7;

intNewCounter = intCounter;

decDiscountAmount = decSubtotal * .2m;

decTotal = decSubtotal – decDiscountAmount;

Assignment Operators…

Slide 13

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Statements that use the same variable on both

sides of the equals sign

decTotal = decTotal + 100m;

decTotal = decTotal – 100m;

decPrice = decPrice * .8m;

Statements that use the shortcut assignment

operators

decTotal += 100m;

decTotal -= 100m;

decPrice *= .8m;

Slide

14

By: S. Sabraz Nawaz

Assignment Operators…

MIT 31043 RAPID APPLICATION DEVELOPMENT

1. Increment and decrement

2. Positive and negative

3. Multiplication, division, and modulus

4. Addition and subtraction

The order of precedence for arithmetic operations

Slide 15

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Common methods for data conversion

Method Description

ToString([format]) A method that converts the value to its

equivalent string representation using the

specified format. If the format is omitted, the

value isn’t formatted.

Parse(string) A static method that converts the specified

string to an equivalent data value.

Slide

16

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Sample ToString formatsVariable Value Format specifier code Output

totalDecimal 1125.6744 ToString(" C" ) $1,125.67

totalDecimal 1125.6744 ToString("N") 1,125.67

totalDecimal 1125.6744 ToString(" N0 ") 1,126

balanceDecimal 1125.6744 ToString(" N3 ") 1,125.674

balanceDecimal 1125.6744 ToString(" F0 ") 1126

pinInteger 123 ToString(" D6 ") 000123

rateDecimal 0.075 ToString(" P " ) 7.50 %

rateDecimal 0.075 ToString(" P3 ") 7.500 %

rateDecimal 0.075 ToString(" P0 ") 8 %

valueInteger –10 ToString(" C " ) ($10.00)

valueInteger –10 ToString(" N " ) –10.00

valueInteger –10 ToString(" D3 “) –010

Code Formats

C or c Currency, P or p Percent, N or n Number, F or f Float, D or d Digits, E or e

Exponential, G or g General Slide 17MIT 31043 RAPID APPLICATION DEVELOPMENT

Some of the static methods of the Convert class

Method Description

ToDecimal(value) Converts the value to the decimal data type.

ToDouble(value) Converts the value to the double data type.

ToInt32(value) Converts the value to the int data type.

ToChar(value) Converts the value to the char data type.

ToBool(value) Converts the value to the bool data type.

ToString(value) Converts the value to the string data type.

Slide

18

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Statements that use ToString and Parse decimal decSales = 2574.98m;

string strSalesString = decSales.ToString(); // decimal to string

decSales = Decimal.Parse(strSalesString); // string to decimal

Conversion statements that use the Convert class decimal decSubtotal = Convert.ToDecimal(txtSubtotal.Text);

// string to decimal

int intYears = Convert.ToInt32(txtYears.Text); // string to int

txtSubtotal.Text = Convert.ToString(decSubtotal);

// decimal to string

int subtotalInt = Convert.ToInt32(decSubtotal);

// decimal to int

By: S. Sabraz NawazSlide

19

MIT 31043 RAPID APPLICATION DEVELOPMENT

More On Variables

Scope of a Variable Lifetime of a Variable

• Programmers use the term scope to

describe the part of a program in which

a variable may be accessed. A variable

is visible only to statements inside the

variable’s scope.

• A local variable’s scope begins at the

variable’s declaration and ends at the

end of the method in which the variable

is declared.

• A local variable cannot be accessed by

statements that are outside the method.

• A local variable cannot be accessed by

code that is inside the method but before

the variable’s declaration.

• A variable’s lifetime is the time period

during which the variable exists in

memory while the program is executing.

• A local variable is created in memory

when the method in which it is declared

starts executing.

• When the method ends, all the method’s

local variables are destroyed.

• So, a local variable’s lifetime is the time

during which the method in which it is

declared is executing.

By: S. Sabraz NawazSlide 20MIT 31043 RAPID APPLICATION DEVELOPMENT

More On Variables

Duplicate Variable Names Assignment Compatibility

• You cannot declare two variables with

the same name in the same scope.

• For example, if you declare a variable

named productDescription in an

event handler, you cannot declare

another variable with that name in the

same event handler.

• You can, however, have variables of

the same name declared in different

methods.

• You can assign a value to a variable

only if the value is compatible with

the variable’s data type. Only strings

are compatible with the string data

type.

By: S. Sabraz NawazSlide 21MIT 31043 RAPID APPLICATION DEVELOPMENT

Understanding Numeric Type Conversion

• When you perform arithmetic with variables or constants of

the same type, the result of the arithmetic retains the same

type.

• For example, when you divide two ints, the result is an int;

when you subtract two doubles, the result is a double.

• Often, however, you need to perform mathematical operations

on different types. For example, in the following code, you

multiply an int by a double:

o int hoursWorked = 36;

o double payRate = 12.35;

o double grossPay = hoursWorked * payRate;

Slide 22MIT 31043 RAPID APPLICATION DEVELOPMENT

Understanding Numeric Type Conversion

• When you perform arithmetic operations with operands of dissimilar types, C# chooses a unifying type for the result and implicitly (or automatically) converts nonconforming operands to the unifying type, which is the type with the higher type precedence.

• The conversion is called an implicit conversion or an implicit cast—the automatic transformation that occurs when a value is assigned to a type with higher precedence.

• For example, if you multiply an int and a double, the result is implicitly a double. This requirement means the result must be stored in a double; if you attempt to assign the result to an int, you will receive a compiler error message like the one shown in Figure.

Slide 23MIT 31043 RAPID APPLICATION DEVELOPMENT

• Error message received when trying to compile a program that attempts to

store a double in an int

• The error message in figure asks “are you missing a cast?” You may

explicitly (or purposefully) override the unifying type imposed by C# by

performing an explicit cast.

• An explicit cast involves placing the desired result type in parentheses

followed by the variable or constant to be cast, as shown below

Slide 24

Understanding Numeric Type Conversion

MIT 31043 RAPID APPLICATION DEVELOPMENT

• Another example is shown here

o The value of bankBalance / 4 is implicitly a double because a double divided

by an int produces a double.

o The double result is then converted to a float before it is stored in

weeklyBudget.

o The float value weeklyBudget is converted to an int before it is stored in

rupees.

o When the float value is converted to an int, the decimal-place values are lost.

• Implicit conversions are not always the result of arithmetic calculations;

simple assignments often result in implicit conversions. For example, if

money is declared as a double, then the following statement implicitly

converts the integer 15 to a double:

o double money;

o money = 15;

Slide 25

Understanding Numeric Type Conversion

MIT 31043 RAPID APPLICATION DEVELOPMENT

The implicit numeric conversions• From sbyte short, int, long, float, double, or decimal

• From byte short, ushort, int, uint, long, ulong, float, double, or decimal

• From short int, long, float, double, or decimal

• From ushort int, uint, long, ulong, float, double, or decimal

• From int long, float, double, or decimal

• From uint long, ulong, float, double, or decimal

• From long float, double, or decimal

• From ulong float, double, or decimal

• From char ushort, int, uint, long, ulong, float, double, or decimal

• From float double

Slide 26MIT 31043 RAPID APPLICATION DEVELOPMENT

Ex 01

• Design the form as below

Slide

27

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Ex 01

• Double click on Convert button and add the following code

Slide

28

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Ex 01

• Double click on Clear button and add the following code

• Double click on Exit button and add the following code

Slide

29

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Ex 02: Invoice Total

Slide

30

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

Ex 02: Code

Slide

31

By: S. Sabraz NawazMIT 31043 RAPID APPLICATION DEVELOPMENT

End