SlideShare a Scribd company logo
Chapter 4C# .NET: Variables
Variables: value and reference typesRecall what we covered in week 1 using pictures to explain the difference between value types and reference types.  This chapter will cover value types in detail
Chapter 4 topicsVariables in detailsNumber – byte, int and longDecimal – float and doubleCharacterBooleanStringImplicit and explicit conversion Numbers, Decimals and their operations (=, +, -, *, / and others)Strings and operations (assigning value, concatenation)
Value reference typesNumber    Types not covered: short, unsigned number such as ulong (unsigned long integer), etcDecimal   Type not covered: decimal (12 bytes)
How to use them - Numbers?byte numberInByte1 = 64;      // OK: auto conversionbyte numberInByte2 = 256;    // ErrorintnumberInByte = 64;          // Default is Integerlong numberInLong1 = 64L;   // L for long numberlong numberInLong2 = 64      // OK: auto conversion
How to use them - Numbers?byte numberInByte1 = 64;      // OK: auto conversionbyte numberInByte2 = 256;    // ErrorintnumberInByte = 64;          // Default is Integerlong numberInLong1 = 64L;   // L for long numberlong numberInLong2 = 64      // OK: auto conversionWhy cannot use small letter L ( l )?
How to use them - Numbers?byte numberInByte1 = 64;      // OK: auto conversionbyte numberInByte2 = 256;    // ErrorintnumberInByte = 64;          // Default is Integerlong numberInLong1 = 64L;   // L for long numberlong numberInLong2 = 64      // OK: auto conversion// Default type is IntegerIf a data is given as  64 without L => data is an integer.   Since numberInLong1 is large enough to store integer 64, there is an auto (implicit) conversion.  Auto (implicit) conversion for numberInByte1 but error for numberInByte2
Declare and initialize// Declare and initialize one variable in one lineint number1 = 5;     // number1 variable is                                 // assigned with a value 5int number2 = 10;// Declare and initialize more than one variable  //   in one lineint number1 = 5, number2 = 10;
Declare and initialize// Declare and initialize one variable in one lineint number1 = 5;     // number1 variable is                                 // assigned with a value 5int number2 = 10;// Declare and initialize more than one variable  //   in one lineint number1 = 5, number2 = 10;When a variable is declared and set with a value at the same time => declare and initializeWhen it is set with value subsequently => assign with value
How to use them - decimals?float numberInFloat1 = 8.0F;    // F for floating number   float numberInFloat2 = 8.0f;     // OK: Small letter Fdouble numberInDouble1 = 8.0;   // Defaultdouble numberInDouble2 = 8.0f;  // OK: Auto conversion
How to use them - decimals?float numberInFloat1 = 8.0F;    // F for floating number   float numberInFloat2 = 8.0f;     // OK: Small letter Fdouble numberInDouble1 = 8.0;   // Defaultdouble numberInDouble2 = 8.0f;  // OK: Auto conversionDo you think the following is OK?  Why?float numberInFloat3 = 8.0;                              //Hint: Default is double
Try it out!Create a new WinForm project: SpfChapter4
Drag and drop a button onto the form
Double click on the button and add the codes to button1_Click event:/*  Number Type */byte numberInByte1 = 64;      // OK: auto conversionbyte numberInByte2 = 256;    // Error: Too big for byteintnumberInByte = 64;           // Default is Integerlong numberInLong1 = 64L;   // L for long numberlong numberInLong2 = 64      // OK: auto conversionlong numberInLong3 = 64l;   // Error: Small letter L int n1 = 5, n2 = 10;                // Declare more than one var// Next page
Try it out!/* Decimal Type */float numberInFloat1 = 8.0F;    // F for floating number   float numberInFloat2 = 8.0f;     // OK: Small letter Fdouble numberInDouble1 = 8.0;   // Defaultdouble numberInDouble2 = 8.0f;  // OK: Auto conversion// Default for decimal is double (8 bytes)float numberInFloat3 = 8.0;     // Error: Too small (4 bytes )                                                 //            to store the double                                                 //            precision (accuracy)
Explicit conversion// Implicit conversion => Automatic conversion// Explicit conversion => do it explicitly// i.e. tell the compiler that you want it to convert and//  that you know what you are doingfloat numberInFloat4 = (float) 8.0;  // No more error
Explicit conversion// Implicit conversion => Automatic conversion// Explicit conversion => do it explicitly// i.e. tell the compiler that you want it to convert and//  that you know what you are doingfloat numberInFloat4 = (float) 8.0;  // No more error// But still give error if the value is too big// For floating type: max value is 3.4e38float numberInFloat5 = (float) 3.5e38;  // Error
Value reference typesOther common value reference types
Special typeStringstring is a reference type but behaves like value type Memory usage is reference typeBehave like value type    string str = “a new string”;   // No need to use New keywordReason: Microsoft wants to make string in .NET safe and fast for programmer to handle sequence of characters.       Good tutorial on C# string:  http://alturl.com/r4qa
How to use them?boolisMoving = true;               // Use true or falseboolhasCompleted = false;char answer = ‘ Y ’;                   // Between ‘ ’string str = “my name”;            // Between “   ”
Try it out!Continue from previous project and add the codes to button1_Click event:boolisMoving = true;               // Boolean use true or falseboolhasCompleted = false;char answer = 'Y';                     // Between ‘ ’string str = "my name";             // Between “   ”
There is a specific relationship between where a variable is defined and where it can be used. This is known as the scope  of the variable. apple only exists in Class2V while june only exists in Class2W. mrPuahexists in CampusMP, Class2V and Class2W.CampusMPmrPuahScope of variableClass2VappleClass2Wjune
Scope of variableA variable once declared, exist only within the code block : { .. }   button1_click( .. )    {         string apple = “ABC”;    // declared here: apple only                                                  //    exist here    }    button2_click(.. )    {         apple = “DEF”;              // Error: apple not defined    }
Scope of variablestring mrPuah = “I am here!”;   // Declared on                                                     // outer { .. }   button1_click( .. )    {mrPuah = “ABC”;             // OK    }    button2_click(.. )    {mrPuah = “DEF”;              // OK    }
Try it out!Continue from previous project and add the codes to button1_Click event:string str = "my name";             // Previous code   {  // Add an inner code blockstr = "change name";         // No error, within inner { .. }        string str2 = “your name";   }str2 = "change name";              // Error: str2 only exist in                                                  // inner { .. }
OperatorsSymbol to perform on expression (part of a statement)For numbers and decimals: =, +, -, *, /, %, ++, -- and                                                  +=, -=, *=, /= For string: =, + (concatenate) and += For the full list of operators, refer to:                    http://alturl.com/bokx
Operators for numbers/decimals
Operators for numbers/decimalsFor complex expression like w + x / y - zUse brackets  ( .. ) to tell compiler which portion to evaluate first.  Eg  (w + x) / (y – z)Otherwise, compiler will use operators precedence rule.  Acronyms like BPODMAS              Refer to:    http://alturl.com/9b8r
Operators for numbers/decimals
Operators for string
Exercise 4.1Textbook from page 52 – 71:Part 1 String Variables in C#.NETPart 2 Assigning Text to a String Variable Part 3 Concatenation in C#.NET Part 4 Comments in C#.NET
Exercise 4.2Textbook from page 71 – 83:Part 5 Integer Variables Part 6 Double and Float Variables Part 7 Double Variables in C# .NET

More Related Content

PPTX
C++ decision making
PPTX
Spf Chapter5 Conditional Logics
PDF
Visual basic asp.net programming introduction
PDF
F sharp - an overview
DOC
Conditional statements in vb script
PPTX
Looping and switch cases
PDF
Learn Java Part 2
PPTX
Switch case and looping statement
C++ decision making
Spf Chapter5 Conditional Logics
Visual basic asp.net programming introduction
F sharp - an overview
Conditional statements in vb script
Looping and switch cases
Learn Java Part 2
Switch case and looping statement

What's hot (17)

PPTX
Microcontroller lec 3
PPT
Lecture 14 - Scope Rules
PPT
Lec 10
PPTX
Looping statements
PPTX
Switch case and looping new
DOCX
Vb script tutorial
PPT
If-else and switch-case
PDF
Monad Fact #6
PPTX
Macasu, gerrell c.
PDF
Lecture13 control statementswitch.ppt
PDF
Basic c# cheat sheet
PPTX
Final project powerpoint template (fndprg) (1)
PDF
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
DOCX
C# language basics (Visual studio)
PDF
Test driven development
PDF
C++ STATEMENTS
PPSX
C lecture 4 nested loops and jumping statements slideshare
Microcontroller lec 3
Lecture 14 - Scope Rules
Lec 10
Looping statements
Switch case and looping new
Vb script tutorial
If-else and switch-case
Monad Fact #6
Macasu, gerrell c.
Lecture13 control statementswitch.ppt
Basic c# cheat sheet
Final project powerpoint template (fndprg) (1)
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
C# language basics (Visual studio)
Test driven development
C++ STATEMENTS
C lecture 4 nested loops and jumping statements slideshare
Ad

Viewers also liked (7)

PPTX
Variables - Value and Reference Type
PDF
C# .net lecture 1 in Hebrew
PPTX
Spf chapter10 events
PDF
C# .net lecture 2 Objects 2
PDF
Day02 01 Advance Feature in C# DH TDT
PDF
C# simplified
PPTX
C# basics
Variables - Value and Reference Type
C# .net lecture 1 in Hebrew
Spf chapter10 events
C# .net lecture 2 Objects 2
Day02 01 Advance Feature in C# DH TDT
C# simplified
C# basics
Ad

Similar to Spf Chapter4 Variables (20)

PPT
Csharp4 basics
PPTX
02. Primitive Data Types and Variables
PDF
C# Language Overview Part I
PPTX
C# overview part 1
PPTX
CSharp Language Overview Part 1
PPTX
CS4443 - Modern Programming Language - I Lecture (2)
PPT
02 Primitive data types and variables
PPTX
Core C# Programming Constructs, Part 1
PPT
C Sharp Jn (1)
PPT
C Sharp Nagina (1)
PPTX
C sharp part 001
PDF
Learning VB.NET Programming Concepts
PPTX
data types in C-Sharp (C#)
PPTX
Lesson 4 Basic Programming Constructs.pptx
PPTX
Java chapter 2
PPTX
Data Types, Variables, and Constants in C# Programming
PPT
Primitive Data Types and Variables Lesson 02
PPTX
unit 1 (1).pptx
PPTX
2 programming with c# i
PPTX
How To Code in C#
Csharp4 basics
02. Primitive Data Types and Variables
C# Language Overview Part I
C# overview part 1
CSharp Language Overview Part 1
CS4443 - Modern Programming Language - I Lecture (2)
02 Primitive data types and variables
Core C# Programming Constructs, Part 1
C Sharp Jn (1)
C Sharp Nagina (1)
C sharp part 001
Learning VB.NET Programming Concepts
data types in C-Sharp (C#)
Lesson 4 Basic Programming Constructs.pptx
Java chapter 2
Data Types, Variables, and Constants in C# Programming
Primitive Data Types and Variables Lesson 02
unit 1 (1).pptx
2 programming with c# i
How To Code in C#

More from Hock Leng PUAH (20)

PDF
ASP.net Image Slideshow
PDF
Using iMac Built-in Screen Sharing
PDF
Hosting SWF Flash file
PDF
PHP built-in functions date( ) and mktime( ) to calculate age from date of birth
PDF
PHP built-in function mktime example
PDF
A simple php exercise on date( ) function
PDF
Integrate jQuery PHP MySQL project to JOOMLA web site
PPTX
Responsive design
PDF
Step by step guide to use mac lion to make hidden folders visible
PPTX
Beautiful web pages
PPT
CSS Basic and Common Errors
PPTX
Connectivity Test for EES Logic Probe Project
PPTX
Logic gate lab intro
PDF
Ohm's law, resistors in series or in parallel
PPTX
Connections Exercises Guide
PPTX
Design to circuit connection
PPTX
NMS Media Services Jobshet 1 to 5 Summary
DOCX
Virtualbox step by step guide
PPTX
Nms chapter 01
PPTX
Pedagogic Innovation to Engage Academically Weaker Students
ASP.net Image Slideshow
Using iMac Built-in Screen Sharing
Hosting SWF Flash file
PHP built-in functions date( ) and mktime( ) to calculate age from date of birth
PHP built-in function mktime example
A simple php exercise on date( ) function
Integrate jQuery PHP MySQL project to JOOMLA web site
Responsive design
Step by step guide to use mac lion to make hidden folders visible
Beautiful web pages
CSS Basic and Common Errors
Connectivity Test for EES Logic Probe Project
Logic gate lab intro
Ohm's law, resistors in series or in parallel
Connections Exercises Guide
Design to circuit connection
NMS Media Services Jobshet 1 to 5 Summary
Virtualbox step by step guide
Nms chapter 01
Pedagogic Innovation to Engage Academically Weaker Students

Recently uploaded (20)

PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
RMMM.pdf make it easy to upload and study
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
History, Philosophy and sociology of education (1).pptx
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
01-Introduction-to-Information-Management.pdf
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
master seminar digital applications in india
PDF
Classroom Observation Tools for Teachers
PPTX
Lesson notes of climatology university.
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
RMMM.pdf make it easy to upload and study
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Microbial diseases, their pathogenesis and prophylaxis
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
What if we spent less time fighting change, and more time building what’s rig...
LDMMIA Reiki Yoga Finals Review Spring Summer
History, Philosophy and sociology of education (1).pptx
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
2.FourierTransform-ShortQuestionswithAnswers.pdf
Yogi Goddess Pres Conference Studio Updates
01-Introduction-to-Information-Management.pdf
A systematic review of self-coping strategies used by university students to ...
Chinmaya Tiranga quiz Grand Finale.pdf
master seminar digital applications in india
Classroom Observation Tools for Teachers
Lesson notes of climatology university.
Microbial disease of the cardiovascular and lymphatic systems
202450812 BayCHI UCSC-SV 20250812 v17.pptx

Spf Chapter4 Variables

  • 1. Chapter 4C# .NET: Variables
  • 2. Variables: value and reference typesRecall what we covered in week 1 using pictures to explain the difference between value types and reference types. This chapter will cover value types in detail
  • 3. Chapter 4 topicsVariables in detailsNumber – byte, int and longDecimal – float and doubleCharacterBooleanStringImplicit and explicit conversion Numbers, Decimals and their operations (=, +, -, *, / and others)Strings and operations (assigning value, concatenation)
  • 4. Value reference typesNumber Types not covered: short, unsigned number such as ulong (unsigned long integer), etcDecimal Type not covered: decimal (12 bytes)
  • 5. How to use them - Numbers?byte numberInByte1 = 64; // OK: auto conversionbyte numberInByte2 = 256; // ErrorintnumberInByte = 64; // Default is Integerlong numberInLong1 = 64L; // L for long numberlong numberInLong2 = 64 // OK: auto conversion
  • 6. How to use them - Numbers?byte numberInByte1 = 64; // OK: auto conversionbyte numberInByte2 = 256; // ErrorintnumberInByte = 64; // Default is Integerlong numberInLong1 = 64L; // L for long numberlong numberInLong2 = 64 // OK: auto conversionWhy cannot use small letter L ( l )?
  • 7. How to use them - Numbers?byte numberInByte1 = 64; // OK: auto conversionbyte numberInByte2 = 256; // ErrorintnumberInByte = 64; // Default is Integerlong numberInLong1 = 64L; // L for long numberlong numberInLong2 = 64 // OK: auto conversion// Default type is IntegerIf a data is given as 64 without L => data is an integer. Since numberInLong1 is large enough to store integer 64, there is an auto (implicit) conversion. Auto (implicit) conversion for numberInByte1 but error for numberInByte2
  • 8. Declare and initialize// Declare and initialize one variable in one lineint number1 = 5; // number1 variable is // assigned with a value 5int number2 = 10;// Declare and initialize more than one variable // in one lineint number1 = 5, number2 = 10;
  • 9. Declare and initialize// Declare and initialize one variable in one lineint number1 = 5; // number1 variable is // assigned with a value 5int number2 = 10;// Declare and initialize more than one variable // in one lineint number1 = 5, number2 = 10;When a variable is declared and set with a value at the same time => declare and initializeWhen it is set with value subsequently => assign with value
  • 10. How to use them - decimals?float numberInFloat1 = 8.0F; // F for floating number float numberInFloat2 = 8.0f; // OK: Small letter Fdouble numberInDouble1 = 8.0; // Defaultdouble numberInDouble2 = 8.0f; // OK: Auto conversion
  • 11. How to use them - decimals?float numberInFloat1 = 8.0F; // F for floating number float numberInFloat2 = 8.0f; // OK: Small letter Fdouble numberInDouble1 = 8.0; // Defaultdouble numberInDouble2 = 8.0f; // OK: Auto conversionDo you think the following is OK? Why?float numberInFloat3 = 8.0; //Hint: Default is double
  • 12. Try it out!Create a new WinForm project: SpfChapter4
  • 13. Drag and drop a button onto the form
  • 14. Double click on the button and add the codes to button1_Click event:/* Number Type */byte numberInByte1 = 64; // OK: auto conversionbyte numberInByte2 = 256; // Error: Too big for byteintnumberInByte = 64; // Default is Integerlong numberInLong1 = 64L; // L for long numberlong numberInLong2 = 64 // OK: auto conversionlong numberInLong3 = 64l; // Error: Small letter L int n1 = 5, n2 = 10; // Declare more than one var// Next page
  • 15. Try it out!/* Decimal Type */float numberInFloat1 = 8.0F; // F for floating number float numberInFloat2 = 8.0f; // OK: Small letter Fdouble numberInDouble1 = 8.0; // Defaultdouble numberInDouble2 = 8.0f; // OK: Auto conversion// Default for decimal is double (8 bytes)float numberInFloat3 = 8.0; // Error: Too small (4 bytes ) // to store the double // precision (accuracy)
  • 16. Explicit conversion// Implicit conversion => Automatic conversion// Explicit conversion => do it explicitly// i.e. tell the compiler that you want it to convert and// that you know what you are doingfloat numberInFloat4 = (float) 8.0; // No more error
  • 17. Explicit conversion// Implicit conversion => Automatic conversion// Explicit conversion => do it explicitly// i.e. tell the compiler that you want it to convert and// that you know what you are doingfloat numberInFloat4 = (float) 8.0; // No more error// But still give error if the value is too big// For floating type: max value is 3.4e38float numberInFloat5 = (float) 3.5e38; // Error
  • 18. Value reference typesOther common value reference types
  • 19. Special typeStringstring is a reference type but behaves like value type Memory usage is reference typeBehave like value type string str = “a new string”; // No need to use New keywordReason: Microsoft wants to make string in .NET safe and fast for programmer to handle sequence of characters. Good tutorial on C# string: http://alturl.com/r4qa
  • 20. How to use them?boolisMoving = true; // Use true or falseboolhasCompleted = false;char answer = ‘ Y ’; // Between ‘ ’string str = “my name”; // Between “ ”
  • 21. Try it out!Continue from previous project and add the codes to button1_Click event:boolisMoving = true; // Boolean use true or falseboolhasCompleted = false;char answer = 'Y'; // Between ‘ ’string str = "my name"; // Between “ ”
  • 22. There is a specific relationship between where a variable is defined and where it can be used. This is known as the scope of the variable. apple only exists in Class2V while june only exists in Class2W. mrPuahexists in CampusMP, Class2V and Class2W.CampusMPmrPuahScope of variableClass2VappleClass2Wjune
  • 23. Scope of variableA variable once declared, exist only within the code block : { .. } button1_click( .. ) { string apple = “ABC”; // declared here: apple only // exist here } button2_click(.. ) { apple = “DEF”; // Error: apple not defined }
  • 24. Scope of variablestring mrPuah = “I am here!”; // Declared on // outer { .. } button1_click( .. ) {mrPuah = “ABC”; // OK } button2_click(.. ) {mrPuah = “DEF”; // OK }
  • 25. Try it out!Continue from previous project and add the codes to button1_Click event:string str = "my name"; // Previous code { // Add an inner code blockstr = "change name"; // No error, within inner { .. } string str2 = “your name"; }str2 = "change name"; // Error: str2 only exist in // inner { .. }
  • 26. OperatorsSymbol to perform on expression (part of a statement)For numbers and decimals: =, +, -, *, /, %, ++, -- and +=, -=, *=, /= For string: =, + (concatenate) and += For the full list of operators, refer to: http://alturl.com/bokx
  • 28. Operators for numbers/decimalsFor complex expression like w + x / y - zUse brackets ( .. ) to tell compiler which portion to evaluate first. Eg (w + x) / (y – z)Otherwise, compiler will use operators precedence rule. Acronyms like BPODMAS Refer to: http://alturl.com/9b8r
  • 31. Exercise 4.1Textbook from page 52 – 71:Part 1 String Variables in C#.NETPart 2 Assigning Text to a String Variable Part 3 Concatenation in C#.NET Part 4 Comments in C#.NET
  • 32. Exercise 4.2Textbook from page 71 – 83:Part 5 Integer Variables Part 6 Double and Float Variables Part 7 Double Variables in C# .NET
  • 33. Exercise 4.3Textbook from page 83 – 92:Part 8 Addition in C# .NET Part 9 Subtraction in C# .NET Part 10 Multiplication and Division in C#.NET
  • 34. SummaryVariables in detailsNumber – byte, int and longDecimal – float and doubleCharacterBooleanStringImplicit and explicit conversion Numbers, Decimals and their operations (=, +, -, *, / and others)Strings and operations (assigning value, concatenation)