Variables and Data Types

Page 1

Variables and Data Types

Learn More @ http://www.learnnowonline.com Copyright Š by Application Developers Training Company


Objectives • Understand how to create variables and assign values • Review the available data types and how they are based on the .NET Framework • See how to convert a variable from one data type to another • Explore operators and how they can be used to change values and compare expressions

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Agenda • • • •

Variables Data Types Converting from One Data Type to Another Operators

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Variables • • • • •

Computer programs manage information Variables are a way to store information Variables exist in memory Created at the start of programs or as needed Variables have three components  Data type  Name  Value

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Naming Variables • Variable names must  Begin with an alphabetic character or an underscore  Contain only alphabetic characters, numbers, and underscores  Contain at least one alphabetic character or number if they begin with an underscore  Be less than 1,023 characters

• Variable names should be descriptive and of reasonable length

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Declaring Variables • Use the Dim keyword to declare a variable and allocate storage space for it in memory • Use the As clause to specify the variable’s data type Dim counter1 As Integer Dim counter2 As Integer = 612 Dim message1, message2, message3 As String message2 = "" message3 = "Hello"

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Declaring Variables • To declare a variable and allocate storage space for it in memory, first specify the data type and then specify the variable’s name

int counter1; int counter2 = 612; string message1, message2, message3; message2 = ""; message3 = "Hello";

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Variable Lifetime and Scope • Variable’s lifetime is length of time it is available  Variable declared in a procedure method will be in memory as long as that procedure method exists

• Variable’s scope determines what code can reference it  Variable declared in a procedure method will be available only to that procedure method  Declare a variable at the class module level for it to be available to multiple procedures methods

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Agenda • • • •

Variables Data Types Converting from One Data Type to Another Operators

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Data Types • All information has a type • Type defines how information will be stored, used, manipulated, and displayed • .NET Framework contains structures and classes that represent various types of data • All data types in Visual Basic and C# are based on a .NET Framework structure or class

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Integer Data Types • SByte – based on System.SByte  Signed 8-bit integer between -128 and 127

• Byte – based on System.Byte  8-bit integer between 0 and 255

• Short – based on System.Int16  16-bit integer between -32,768 and 32,767

• UShort – based on System.Int16  16-bit unsigned integer between 0 and 65,535

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Integer Data Types • Integer – based on System.Int32  32-bit integer between -2,147,483,648 and 2,147,483,647

• UInteger – based on System.Int32  32-bit unsigned integer between 0 and 4,294,967,295

• Long – based on System.Int64  64-bit integer between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807

• ULong – based on System.Int64  64-bit unsigned integer between 0 and 18,446,744,073,709,551,615 Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Integer Data Types • sbyte – based on System.SByte  Signed 8-bit integer between -128 and 127

• byte – based on System.Byte  8-bit integer between 0 and 255

• short – based on System.Int16  16-bit integer between -32,768 and 32,767

• ushort – based on System.Int16  16-bit unsigned integer between 0 and 65,535

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Integer Data Types • int – based on System.Int32  32-bit integer between -2,147,483,648 and 2,147,483,647

• uint – based on System.Int32  32-bit unsigned integer between 0 and 4,294,967,295

• long – based on System.Int64  64-bit integer between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807

• ulong – based on System.Int64  64-bit unsigned integer between 0 and 18,446,744,073,709,551,615 Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Choosing an Integer Data Type • Choose a data type that is appropriate for the data you will store • Balance memory requirement and performance  Integer requires twice as much storage space (4 bytes) than Short (2 bytes)  Integer and Long are more efficient than Byte or Short because .NET Framework represents numbers as 32-bit or 64-bit values

• Use Integer unless you have valid concerns about memory usage Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Choosing an Integer Data Type • Choose a data type that is appropriate for the data you will store • Balance memory requirement and performance  int requires twice as much storage space (4 bytes) than short (2 bytes)  int and long are more efficient than Byte or short because .NET Framework represents numbers as 32bit or 64-bit values

• Use int unless you have valid concerns about memory usage Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Integer Data Types Fields and Methods • MinValue and MaxValue represent low and high end of range of values • ToString returns string representation of value  Specify format to control how string is displayed

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Floating-Point Data Types • Single – based on System.Single  32-bit single-precision floating point number between -3.402823 x 1038 and -1.401298 / 1045 for negative values and 1.401298 / 1045 and 3.402823 x 1038 for positive values

• Double – based on System.Double  64-bit double-precision floating point number between -1.79769313486231570 x 10308 and -4.94065645841246544 / 10324 for negative values and between 4.94065645841246544 x 10324 and 1.79769313486231570 x 10308 for positive values

• Use Double unless you have valid concerns about memory usage

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Floating-Point Data Types • float – based on System.Single  32-bit single-precision floating point number between -3.402823 x 1038 and -1.401298 / 1045 for negative values and 1.401298 / 1045 and 3.402823 x 1038 for positive values

• double – based on System.Double  64-bit double-precision floating point number between -1.79769313486231570 x 10308 and -4.94065645841246544 / 10324 for negative values and between 4.94065645841246544 x 10324 and 1.79769313486231570 x 10308 for positive values

• Use double unless you have valid concerns about memory usage

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Decimal Data Type • Based on System.Decimal  128-bit number between -79,228,162,514,264,337,593,543,950,335 and 79,228,162,514,264,337,593,543,950,335 with no decimal places and between -7.9228162514264337593543950335 and 7.9228162514264337593543950335 with up to 28 decimal places

• Holds numbers of lesser magnitude than floating points, but with greater precision • Use when you need the utmost in precision, especially for financial calculations Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Decimal Data Type Fields and Methods • Truncate returns integer part and discards fractional part • Round rounds to nearest integer or to a specified number of decimal places • Floor rounds to integer smaller than or equal to the value • Ceiling rounds to integer greater than or equal to the value

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Char Data Type • Based on System.Char  16-bit numeric value between 0 to 65535

• Holds code points, or character codes, representing a single Unicode character  The first 128 code points, numbers 0 through 127, are the ASCII character set

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Char Data Type Methods • ConvertFromUtf32 returns Unicode character associated with code point • ConvertToUtf32 returns code point associated with Unicode character

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Char Data Type Methods • • • • • • • • • • •

IsControl indicates if a tab, carriage return, or line feed IsDigit indicates if a decimal digit IsLetter indicates if an alphabetic letter IsLetterOrDigit indicates if a letter or digit IsLower indicates if a lowercase letter IsNumber indicates if a number IsPunctuation indicates if a punctuation mark IsSeparator indicates if a separator, such as a space IsSymbol indicates if a symbol, such as a + or IsUpper indicates if an uppercase letter IsWhitespace indicates if white space Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


String Data Type • Based on System.String  Represents a series of 0 to 2 billion characters

• To include quotation marks in a string, use two in a row  Dim greeting As String = "Hello ""Robert"""

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Boolean Data Type • Based on System.Boolean  0 (True) or 1 (False)

• Used to test conditions If firstVariable > secondVariable Then Console.WriteLine("{0} is greater than {1}", _ firstVariable, secondVariable) End If

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Date Data Type • Based on System.DateTime  64 bit values representing dates ranging from 01/01/0001 through 12/31/9999 and times from 12:00:00 AM (midnight) through 11:59:59.9999999 PM

• Enclose the date within # characters  Dim nextCentury As Date = #1/1/2100#

• Must use M/d/yyyy format • Consider using DateTime rather than Date

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


String Data Type • Based on System.String  Represents a series of 0 to 2 billion characters

• Use escape sequence (\) or preface the string with @ to include quotation marks and backslashes in strings  string greeting1 = "Hello \" Robert\""; string greeting2 = @"Hello "" Robert""";

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Bool Data Type • Based on System.Boolean  0 (True) or 1 (False)

• Used to test conditions if (firstVariable > secondVariable) { Console.WriteLine("{0} is greater than {1}", firstVariable, secondVariable); }

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Object Data Type • Based on System.Object • Can contain any data type, including another object • Use GetType to determine what type of data is stored • Contains a pointer to the value in memory, not actual data

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Agenda • • • • •

Variables Data Types Converting from One Data Type to Another Constants, Enumerations, and Structures Operators

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Converting to Another Data Type • Widening conversion  New data type can store all of the values of the original data type  Compiler will make the conversion for you

• Narrowing conversion  New data type cannot store all of the values of the original data type  Loss of data could result  Need to make the conversion in code

• Make your conversions explicitly in code  Code is more readable and understandable Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Converting to Another Data Type • Use a conversion function  shortValue = shortValue + CShort(byteValue)

• Convert class includes a conversion method for each data type  Convert.ToSingle(longValue)

• Parse method converts a string to a data type  Single.Parse(longValue.ToString())

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Converting to Another Data Type • Use a cast operator  shortValue = (short)(shortValue + byteValue);

• Convert class includes a conversion method for each data type  Convert.ToSingle(longValue);

• Parse method converts a string to a data type  Single.Parse(longValue.ToString());

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Value Types and Reference Types • Value type variables directly store their values  Stored in the stack, pool of memory allocated by runtime for value types  Declared in code and runtime allocates proper amount of memory for them  Efficient because space has already been allocated on stack

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Value Types and Reference Types • Reference type variables store a reference to their values  Stored in the heap, a pool of memory whose size is dynamic  Value is stored in the stack, but variable stores a reference to a value  Reference is used to find a value each time a variable is accessed in code  Less efficient than value types

Learn More @ http://www.learnnowonline.com \ Copyright © by Application Developers Training Company


Value Types and Reference Types • Boxing  A value type is converted to a reference type  .NET Framework copies the value to the heap and returns a reference to the value

• Unboxing  A reference type is converted to a value type  NET Framework uses the reference to copy the value back into a value type

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Constants • Declared like variables • Value cannot be changed in code

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Enumerations • Collection of related constants • Has a name and a numeric data type • Has a number of fields, each with a name and a value

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Structures • Structures are user-defined data types • Similar to enumerations in that they are a collection of values • Can contain any data type

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Structs • Structs are user-defined data types • Similar to enumerations in that they are a collection of values • Can contain any data type

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Agenda • • • •

Variables Data Types Converting from One Data Type to Another Operators

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Operators • Perform an action on one or more values and return the result of the operation      

Arithmetic operators String operators Assignment operators Comparison operators Logical operators Type operators

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Arithmetic Operators • Perform basic arithmetic on one or more variables  + adds two numbers or converts a negative number into a positive number  - subtracts two numbers or converts a positive number into a negative number  * multiplies two numbers  / divides two numbers  Mod divides two numbers and returns only the remainder of the result  \ divides two numbers and returns only the integer part of the result  ^ raises a number to the power of another number

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


String Operators • & and + operators concatenate, or add, two strings together to produce a new string • Use Like to determine if a string matches a pattern  Use a * in the pattern to match to zero or more characters  Use a ? in the pattern to match to any single character  Use a # in the pattern to match to any single digit  Use a [] in the pattern to match to a list of characters Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Assignment Operators • Perform similar operations as arithmetic operators  += adds two numbers or converts a negative number into a positive number  -= subtracts two numbers or converts a positive number into a negative number  *= multiplies two numbers  /= divides two numbers  \= divides two numbers and returns only the integer part of the result  ^= raises a number to the power of another number Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Comparison Operators • Used to compare two values  = returns true if two values are equal  <> returns true if two values are not equal  > returns true if the first value is greater than the second  < returns true if the first value is less than the second  >= returns true if the first value is greater than or equal to the second  <= returns true if the first value is less than or equal to the second Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Logical Operators • Used to compare two expressions        

A And B returns true if both A and B are true A Or B returns true if either A or B is true Not A returns true if A is not true A Xor B returns true if either A or B is true, but both of them are not true A AndAlso B returns true if both A and B are true. Does not evaluate B if A is not true. A OrElse B returns true if either A or B is true. Does not evaluate B if A is true. A Is B returns true if A and B refer to the same object A IsNot B returns true if A and B do not refer to the same object Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Type Operators • Test whether an object is of a particular data type Dim object1 As Object object1 = 7 If TypeOf object1 Is Integer Then Console.WriteLine("object1 = 7 and is type Integer") End If

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Arithmetic Operators • Perform basic arithmetic on one or more variables  + adds two numbers or converts a negative number into a positive number  - subtracts two numbers or converts a positive number into a negative number  * multiplies two numbers  / divides two numbers  % divides two numbers and returns only the remainder of the result  ++ increments a number by 1  -- decrements a number by 1 Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


String Operators • + operator concatenates, or adds, two strings together to produce a new string

Learn More @ http://www.learnnowonline.com Copyright Š by Application Developers Training Company


Assignment Operators • Perform similar operations as arithmetic operators  += adds two numbers or converts a negative number into a positive number  -= subtracts two numbers or converts a positive number into a negative number  *= multiplies two numbers  /= divides two numbers  %= divides two numbers and returns only the remainder of the result Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Comparison Operators • Used to compare two values  == returns true if two values are equal  != returns true if two values are not equal  > returns true if the first value is greater than the second  < returns true if the first value is less than the second  >= returns true if the first value is greater than or equal to the second  <= returns true if the first value is less than or equal to the second Learn More @ http://www.learnnowonline.com \ Copyright © by Application Developers Training Company


Logical Operators • Used to compare two expressions A & B returns true if both A and B are true A | B returns true if either A or B is true ! A returns true if A is not true A ^ B returns true if either A or B is true but both of them are not true  A && B returns true if both A and B are true. Does not evaluate B if A is not true.  A || B returns true if either A or B is true. Does not evaluate B if A is true.    

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Type Operators • Test whether an object is of a particular data type object object1; object1 = 7; if (object1 is int) { Console.WriteLine("object1 = 7 and is type Integer"); }

Learn More @ http://www.learnnowonline.com Copyright Š by Application Developers Training Company


Learn More! • This is an excerpt from a larger course. Visit www.learnnowonline.com for the full details! • Learn more about .NET on SlideShare: • Getting Started with .NET

Learn More @ http://www.learnnowonline.com Copyright © by Application Developers Training Company


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.