SlideShare a Scribd company logo
Primitive Data
Types andVariables
Creating and RunningYour First C# Program
Svetlin Nakov
Telerik Corporation
www.telerik.com
Table of Contents
1. Primitive DataTypes
 Integer
 Floating-Point / Decimal Floating-Point
 Boolean
 Character
 String
 Object
2. Declaring and UsingVariables
 Identifiers
 DeclaringVariables and AssigningValues
 Literals
3. Nullable types
2
Primitive DataTypes
How Computing Works?
Computers are machines that process data
 Data is stored in the computer memory in
variables
 Variables have name, data type and value
Example of variable definition and assignment
in C#
int count = 5;
Data type
Variable name
Variable value
4
What Is a DataType?
A data type:
Is a domain of values of similar characteristics
Defines the type of information stored in the
computer memory (in a variable)
Examples:
Positive integers: 1, 2, 3, …
Alphabetical characters: a, b, c, …
Days of week: Monday, Tuesday, …
5
DataType Characteristics
A data type has:
Name (C# keyword or .NET type)
Size (how much memory is used)
Default value
Example:
Integer numbers in C#
Name: int
Size: 32 bits (4 bytes)
Default value: 0
6
IntegerTypes
What are IntegerTypes?
Integer types:
Represent whole numbers
May be signed or unsigned
Have range of values, depending on the size of
memory used
The default value of integer types is:
0 – for integer types, except
0L – for the long type
8
IntegerTypes
Integer types are:
sbyte (-128 to 127): signed 8-bit
byte (0 to 255): unsigned 8-bit
short (-32,768 to 32,767): signed 16-bit
ushort (0 to 65,535): unsigned 16-bit
int (-2,147,483,648 to 2,147,483,647): signed
32-bit
uint (0 to 4,294,967,295): unsigned 32-bit
9
IntegerTypes (2)
More integer types:
long (-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807): signed 64-bit
ulong (0 to 18,446,744,073,709,551,615):
unsigned 64-bit
10
MeasuringTime – Example
Depending on the unit of measure we may use
different data types:
byte centuries = 20; // Usually a small number
ushort years = 2000;
uint days = 730480;
ulong hours = 17531520; // May be a very big number
Console.WriteLine("{0} centuries is {1} years, or {2}
days, or {3} hours.", centuries, years, days, hours);
11
IntegerTypes
Live Demo
Floating-Point and Decimal
Floating-PointTypes
What are Floating-PointTypes?
Floating-point types:
Represent real numbers
May be signed or unsigned
Have range of values and different precision
depending on the used memory
Can behave abnormally in the calculations
14
Floating-Point Types
Floating-point types are:
float (±1.5 × 10−45 to ±3.4 × 1038): 32-bits,
precision of 7 digits
double (±5.0 × 10−324 to ±1.7 × 10308): 64-bits,
precision of 15-16 digits
The default value of floating-point types:
Is 0.0F for the float type
Is 0.0D for the double type
15
PI Precision – Example
See below the difference in precision when using
float and double:
NOTE:The “f” suffix in the first statement!
 Real numbers are by default interpreted as double!
 One should explicitly convert them to float
float floatPI = 3.141592653589793238f;
double doublePI = 3.141592653589793238;
Console.WriteLine("Float PI is: {0}", floatPI);
Console.WriteLine("Double PI is: {0}", doublePI);
16
Abnormalities in the
Floating-Point Calculations
Sometimes abnormalities can be observed
when using floating-point numbers
Comparing floating-point numbers can not be
performed directly with the == operator
Example:
double a = 1.0f;
double b = 0.33f;
double sum = 1.33f;
bool equal = (a+b == sum); // False!!!
Console.WriteLine("a+b={0} sum={1} equal={2}",
a+b, sum, equal);
17
Decimal Floating-PointTypes
There is a special decimal floating-point
real number type in C#:
decimal (±1,0 × 10-28 to ±7,9 × 1028): 128-bits,
precision of 28-29 digits
Used for financial calculations
No round-off errors
Almost no loss of precision
The default value of decimal type is:
0.0M (M is the suffix for decimal numbers)
18
Floating-Point and Decimal
Floating-PointTypes
Live Demo
BooleanType
The Boolean DataType
The Boolean data type:
Is declared by the bool keyword
Has two possible values: true and false
Is useful in logical expressions
The default value is false
21
BooleanValues – Example
Example of boolean variables taking values of
true or false:
int a = 1;
int b = 2;
bool greaterAB = (a > b);
Console.WriteLine(greaterAB); // False
bool equalA1 = (a == 1);
Console.WriteLine(equalA1); // True
22
BooleanType
Live Demo
CharacterType
The Character DataType
The character data type:
Represents symbolic information
Is declared by the char keyword
Gives each symbol a corresponding integer code
Has a '0' default value
Takes 16 bits of memory (from U+0000 to
U+FFFF)
25
Characters and Codes
The example below shows that every symbol
has an its unique Unicode code:
char symbol = 'a';
Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);
symbol = 'b';
Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);
symbol = 'A';
Console.WriteLine("The code of '{0}' is: {1}",
symbol, (int) symbol);
26
CharacterType
Live Demo
StringType
The String DataType
The string data type:
Represents a sequence of characters
Is declared by the string keyword
Has a default value null (no value)
Strings are enclosed in quotes:
Strings can be concatenated
Using the + operator
string s = "Microsoft .NET Framework";
29
Saying Hello – Example
Concatenating the two names of a person to
obtain his full name:
NOTE: a space is missing between the two
names!We have to add it manually
string firstName = "Ivan";
string lastName = "Ivanov";
Console.WriteLine("Hello, {0}!n", firstName);
string fullName = firstName + " " + lastName;
Console.WriteLine("Your full name is {0}.",
fullName);
30
StringType
Live Demo
ObjectType
The ObjectType
The object type:
Is declared by the object keyword
Is the base type of all other types
Can hold values of any type
33
Using Objects
Example of an object variable taking different
types of data:
object dataContainer = 5;
Console.Write("The value of dataContainer is: ");
Console.WriteLine(dataContainer);
dataContainer = "Five";
Console.Write("The value of dataContainer is: ");
Console.WriteLine(dataContainer);
34
Objects
Live Demo
IntroducingVariables
What Is aVariable?
A variable is a:
Placeholder of information that can usually be
changed at run-time
Variables allow you to:
Store information
Retrieve the stored information
Manipulate the stored information
37
Variable Characteristics
A variable has:
Name
Type (of stored data)
Value
Example:
Name: counter
Type: int
Value: 5
int counter = 5;
38
Declaring And Using
Variables
DeclaringVariables
When declaring a variable we:
Specify its type
Specify its name (called identifier)
May give it an initial value
The syntax is the following:
Example:
<data_type> <identifier> [= <initialization>];
int height = 200;
40
Identifiers
Identifiers may consist of:
Letters (Unicode)
Digits [0-9]
Underscore "_"
Identifiers
Can begin only with a letter or an underscore
Cannot be a C# keyword
41
Identifiers (2)
Identifiers
Should have a descriptive name
It is recommended to use only Latin letters
Should be neither too long nor too short
Note:
In C# small letters are considered different than
the capital letters (case sensitivity)
42
Identifiers – Examples
Examples of correct identifiers:
Examples of incorrect identifiers:
int new; // new is a keyword
int 2Pac; // Cannot begin with a digit
int New = 2; // Here N is capital
int _2Pac; // This identifiers begins with _
string поздрав = "Hello"; // Unicode symbols used
// The following is more appropriate:
string greeting = "Hello";
int n = 100; // Undescriptive
int numberOfClients = 100; // Descriptive
// Overdescriptive identifier:
int numberOfPrivateClientOfTheFirm = 100;
43
AssigningValues
ToVariables
AssigningValues
Assigning of values to variables
Is achieved by the = operator
The = operator has
Variable identifier on the left
Value of the corresponding data type on the
right
Could be used in a cascade calling, where
assigning is done from right to left
45
AssigningValues – Examples
Assigning values example:
int firstValue = 5;
int secondValue;
int thirdValue;
// Using an already declared variable:
secondValue = firstValue;
// The following cascade calling assigns
// 3 to firstValue and then firstValue
// to thirdValue, so both variables have
// the value 3 as a result:
thirdValue = firstValue = 3; // Avoid this!
46
Initializing Variables
Initializing
Is assigning of initial value
Must be done before the variable is used!
Several ways of initializing:
By using the new keyword
By using a literal expression
By referring to an already initialized variable
47
Initialization – Examples
Example of some initializations:
// The following would assign the default
// value of the int type to num:
int num = new int(); // num = 0
// This is how we use a literal expression:
float heightInMeters = 1.74f;
// Here we use an already initialized variable:
string greeting = "Hello World!";
string message = greeting;
48
Assigning and
InitializingVariables
Live Demo
Literals
What are Literals?
Literals are:
Representations of values in the source code
There are six types of literals
Boolean
Integer
Real
Character
String
The null literal
51
Boolean and Integer Literals
The boolean literals are:
true
false
The integer literals:
Are used for variables of type int, uint, long,
and ulong
Consist of digits
May have a sign (+,-)
May be in a hexadecimal format
52
Integer Literals
Examples of integer literals
The '0x' and '0X' prefixes mean a
hexadecimal value, e.g. 0xA8F1
The 'u' and 'U' suffixes mean a ulong or uint
type, e.g. 12345678U
The 'l' and 'L' suffixes mean a long or ulong
type, e.g. 9876543L
53
Integer Literals – Example
Note: the letter ‘l’ is easily confused with the
digit ‘1’ so it’s better to use ‘L’!!!
// The following variables are
// initialized with the same value:
int numberInHex = -0x10;
int numberInDec = -16;
// The following causes an error,
because 234u is of type uint
int unsignedInt = 234u;
// The following causes an error,
because 234L is of type long
int longInt = 234L;
54
Real Literals
The real literals:
Are used for values of type float, double and
decimal
May consist of digits, a sign and “.”
May be in exponential notation: 6.02e+23
The “f” and “F” suffixes mean float
The “d” and “D” suffixes mean double
The “m” and “M” suffixes mean decimal
The default interpretation is double
55
Real Literals – Example
Example of incorrect float literal:
A correct way to assign floating-point value
(using also the exponential format):
56
// The following causes an error
// because 12.5 is double by default
float realNumber = 12.5;
// The following is the correct
// way of assigning the value:
float realNumber = 12.5f;
// This is the same value in exponential format:
realNumber = 1.25e+7f;
Character Literals
The character literals:
Are used for values of the char type
Consist of two single quotes surrounding the
character value: '<value>'
The value may be:
Symbol
The code of the symbol
Escaping sequence
57
Escaping Sequences
Escaping sequences are:
Means of presenting a symbol that is usually
interpreted otherwise (like ')
Means of presenting system symbols (like the
new line symbol)
Common escaping sequences are:
 ' for single quote " for double quote
  for backslash n for new line
 uXXXX for denoting any other Unicode symbol
58
Character Literals – Example
Examples of different character literals:
char symbol = 'a'; // An ordinary symbol
symbol = 'u006F'; // Unicode symbol code in
// a hexadecimal format
symbol = 'u8449'; // 葉 (Leaf in Traditional Chinese)
symbol = '''; // Assigning the single quote symbol
symbol = ''; // Assigning the backslash symbol
symbol = 'n'; // Assigning new line symbol
symbol = 't'; // Assigning TAB symbol
symbol = "a"; // Incorrect: use single quotes
59
String Literals
String literals:
Are used for values of the string type
Consist of two double quotes surrounding the
value: "<value>"
May have a @ prefix which ignores the used
escaping sequences: @"<value>"
The value is a sequence of character literals
string s = "I am a sting literal";
60
String Literals – Example
Benefits of quoted strings (the @ prefix):
In quoted strings " is used instead of ""!
// Here is a string literal using escape sequences
string quotation = ""Hello, Jude", he said.";
string path = "C:WINNTDartsDarts.exe";
// Here is an example of the usage of @
quotation = @"""Hello, Jimmy!"", she answered.";
path = @"C:WINNTDartsDarts.exe";
string str = @"some
text";
61
String Literals
Live Demo
NullableTypes
63
NullableTypes
Nullable types are instances of the
System.Nullable struct
Wrapper over the primitive types
E.g. int?, double?, etc.
Nullabe type can represent the normal range
of values for its underlying value type, plus an
additional null value
Useful when dealing with Databases or other
structures that have default value null
NullableTypes – Example
int? someInteger = null;
Console.WriteLine(
"This is the integer with Null value -> " + someInteger);
someInteger = 5;
Console.WriteLine(
"This is the integer with value 5 -> " + someInteger);
double? someDouble = null;
Console.WriteLine(
"This is the real number with Null value -> "
+ someDouble);
someDouble = 2.5;
Console.WriteLine(
"This is the real number with value 5 -> " +
someDouble);
Example with Integer:
Example with Double:
NullableTypes
Live Demo
66
Questions?
Primitive Data
Types andVariables
http://academy.telerik.com
Exercises
1. Declare five variables choosing for each of them the
most appropriate of the types byte, sbyte, short,
ushort, int, uint, long, ulong to represent the
following values: 52130, -115, 4825932, 97, -10000.
2. Which of the following values can be assigned to a
variable of type float and which to a variable of
type double: 34.567839023, 12.345, 8923.1234857,
3456.091?
3. Write a program that safely compares floating-point
numbers with precision of 0.000001.
68
Exercises (2)
4. Declare an integer variable and assign it with the
value 254 in hexadecimal format. Use Windows
Calculator to find its hexadecimal representation.
5. Declare a character variable and assign it with the
symbol that has Unicode code 72. Hint: first use the
Windows Calculator to find the hexadecimal
representation of 72.
6. Declare a boolean variable called isFemale and
assign an appropriate value corresponding to your
gender.
69
Exercises (3)
7. Declare two string variables and assign them with
“Hello” and “World”. Declare an object variable and
assign it with the concatenation of the first two
variables (mind adding an interval). Declare a third
string variable and initialize it with the value of the
object variable (you should perform type casting).
8. Declare two string variables and assign them with
following value:
Do the above in two different ways: with and
without using quoted strings.
The "use" of quotations causes difficulties.
70
Exercises (4)
9. Write a program that prints an isosceles triangle of
9 copyright symbols ©. Use Windows Character
Map to find the Unicode code of the © symbol.
10. A marketing firm wants to keep record of its
employees. Each record would have the following
characteristics – first name, family name, age,
gender (m or f), ID number, unique employee
number (27560000 to 27569999). Declare the
variables needed to keep the information for a
single employee using appropriate data types and
descriptive names.
11. Declare two integer variables and assign them with
5 and 10 and after that exchange their values.
71

More Related Content

What's hot

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
siragezeynu
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
Manzoor ALam
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8
Abou Bakr Ashraf
 
Visula C# Programming Lecture 7
Visula C# Programming Lecture 7Visula C# Programming Lecture 7
Visula C# Programming Lecture 7
Abou Bakr Ashraf
 
02 data types in java
02 data types in java02 data types in java
02 data types in java
রাকিন রাকিন
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
Sherwin Banaag Sapin
 
Chapter 4 Powerpoint
Chapter 4 PowerpointChapter 4 Powerpoint
Chapter 4 PowerpointGus Sandoval
 
C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
Data Handling
Data HandlingData Handling
Data Handling
Praveen M Jigajinni
 
Chapter 2 basic element of programming
Chapter 2 basic element of programming Chapter 2 basic element of programming
Chapter 2 basic element of programming Zul Aiman
 
Cpprm
CpprmCpprm
Cpprm
Shawne Lee
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
Eduardo Bergavera
 
Moving Average Filter in C
Moving Average Filter in CMoving Average Filter in C
Moving Average Filter in C
Colin
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Dushmanta Nath
 
C programming session 01
C programming session 01C programming session 01
C programming session 01Dushmanta Nath
 
Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++
Ankur Pandey
 
C Programming Language
C Programming LanguageC Programming Language
C Programming Language
RTS Tech
 

What's hot (19)

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8
 
Visula C# Programming Lecture 7
Visula C# Programming Lecture 7Visula C# Programming Lecture 7
Visula C# Programming Lecture 7
 
02 data types in java
02 data types in java02 data types in java
02 data types in java
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
 
Chapter 4 Powerpoint
Chapter 4 PowerpointChapter 4 Powerpoint
Chapter 4 Powerpoint
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Data Handling
Data HandlingData Handling
Data Handling
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
Chapter 2 basic element of programming
Chapter 2 basic element of programming Chapter 2 basic element of programming
Chapter 2 basic element of programming
 
Cpprm
CpprmCpprm
Cpprm
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Moving Average Filter in C
Moving Average Filter in CMoving Average Filter in C
Moving Average Filter in C
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
 
Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++
 
C Programming Language
C Programming LanguageC Programming Language
C Programming Language
 

Viewers also liked

Basic Efficiency Resource: A framework for measuring the relative performance...
Basic Efficiency Resource: A framework for measuring the relative performance...Basic Efficiency Resource: A framework for measuring the relative performance...
Basic Efficiency Resource: A framework for measuring the relative performance...
Brian Cugelman, PhD (AlterSpark)
 
Outline of nursing research ppt1
Outline of nursing research ppt1Outline of nursing research ppt1
Outline of nursing research ppt1
Nursing Path
 
RESEARCH: variables, assumptions, and hypothese
RESEARCH: variables, assumptions, and hypotheseRESEARCH: variables, assumptions, and hypothese
RESEARCH: variables, assumptions, and hypotheseJane-vy Labarosa
 
Research Methods in Psychology: Ethics
Research Methods in Psychology: EthicsResearch Methods in Psychology: Ethics
Research Methods in Psychology: EthicsCrystal Delosa
 
PSYA4 - Research methods
PSYA4 - Research methodsPSYA4 - Research methods
PSYA4 - Research methodsNicky Burt
 
Introduction to Research Ethics
Introduction to Research EthicsIntroduction to Research Ethics
Introduction to Research Ethics
Umm Al-Qura University Faculty of Dentistry
 
Ethics in research
Ethics in researchEthics in research
Ethics in research
Mira K Desai
 
Basic variables ppt
Basic variables pptBasic variables ppt
Basic variables ppt
Shaker Middle School
 
content analysis
content analysiscontent analysis
content analysis
Essam Obaid
 
Variables And Measurement Scales
Variables And Measurement ScalesVariables And Measurement Scales
Variables And Measurement Scalesguesta861fa
 
content analysis and discourse analysis
content analysis and discourse analysiscontent analysis and discourse analysis
content analysis and discourse analysis
Rudy Banuta
 

Viewers also liked (15)

Quants
QuantsQuants
Quants
 
Basic Efficiency Resource: A framework for measuring the relative performance...
Basic Efficiency Resource: A framework for measuring the relative performance...Basic Efficiency Resource: A framework for measuring the relative performance...
Basic Efficiency Resource: A framework for measuring the relative performance...
 
Outline of nursing research ppt1
Outline of nursing research ppt1Outline of nursing research ppt1
Outline of nursing research ppt1
 
RESEARCH: variables, assumptions, and hypothese
RESEARCH: variables, assumptions, and hypotheseRESEARCH: variables, assumptions, and hypothese
RESEARCH: variables, assumptions, and hypothese
 
Research Methods in Psychology: Ethics
Research Methods in Psychology: EthicsResearch Methods in Psychology: Ethics
Research Methods in Psychology: Ethics
 
Content analysis
Content analysisContent analysis
Content analysis
 
Research ethics
Research ethicsResearch ethics
Research ethics
 
PSYA4 - Research methods
PSYA4 - Research methodsPSYA4 - Research methods
PSYA4 - Research methods
 
Introduction to Research Ethics
Introduction to Research EthicsIntroduction to Research Ethics
Introduction to Research Ethics
 
Ethics in research
Ethics in researchEthics in research
Ethics in research
 
Basic variables ppt
Basic variables pptBasic variables ppt
Basic variables ppt
 
content analysis
content analysiscontent analysis
content analysis
 
Research design
Research designResearch design
Research design
 
Variables And Measurement Scales
Variables And Measurement ScalesVariables And Measurement Scales
Variables And Measurement Scales
 
content analysis and discourse analysis
content analysis and discourse analysiscontent analysis and discourse analysis
content analysis and discourse analysis
 

Similar to 02 Primitive data types and variables

02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
Intro C# Book
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
Hossein Zahed
 
C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part IDoncho Minkov
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
Neeru Mittal
 
variablesfinal-170820055428 data type results
variablesfinal-170820055428 data type resultsvariablesfinal-170820055428 data type results
variablesfinal-170820055428 data type results
atifmugheesv
 
JAVA LESSON-01.pptx
JAVA LESSON-01.pptxJAVA LESSON-01.pptx
JAVA LESSON-01.pptx
StephenOczon1
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
PriyadarshiniS28
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
Md. Mahedee Hasan
 
data types in C-Sharp (C#)
data types in C-Sharp (C#)data types in C-Sharp (C#)
data types in C-Sharp (C#)
Abid Kohistani
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
Rasan Samarasinghe
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
Rasan Samarasinghe
 
C Sharp Nagina (1)
C Sharp Nagina (1)C Sharp Nagina (1)
C Sharp Nagina (1)
guest58c84c
 
C Sharp Jn (1)
C Sharp Jn (1)C Sharp Jn (1)
C Sharp Jn (1)jahanullah
 
C#
C#C#
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
Literals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiers
Tanishq Soni
 

Similar to 02 Primitive data types and variables (20)

02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
C# Language Overview Part I
C# Language Overview Part IC# Language Overview Part I
C# Language Overview Part I
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
 
variablesfinal-170820055428 data type results
variablesfinal-170820055428 data type resultsvariablesfinal-170820055428 data type results
variablesfinal-170820055428 data type results
 
JAVA LESSON-01.pptx
JAVA LESSON-01.pptxJAVA LESSON-01.pptx
JAVA LESSON-01.pptx
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
 
data types in C-Sharp (C#)
data types in C-Sharp (C#)data types in C-Sharp (C#)
data types in C-Sharp (C#)
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
C Sharp Nagina (1)
C Sharp Nagina (1)C Sharp Nagina (1)
C Sharp Nagina (1)
 
C Sharp Jn (1)
C Sharp Jn (1)C Sharp Jn (1)
C Sharp Jn (1)
 
C#
C#C#
C#
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Literals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiers
 
M C6java2
M C6java2M C6java2
M C6java2
 

More from maznabili

22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solving
maznabili
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii
maznabili
 
21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-i
maznabili
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
maznabili
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexity
maznabili
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
maznabili
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
maznabili
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
maznabili
 
15 Text files
15 Text files15 Text files
15 Text files
maznabili
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
maznabili
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
maznabili
 
12 Exceptions handling
12 Exceptions handling12 Exceptions handling
12 Exceptions handling
maznabili
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
maznabili
 
10 Recursion
10 Recursion10 Recursion
10 Recursion
maznabili
 
09 Methods
09 Methods09 Methods
09 Methods
maznabili
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systems
maznabili
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
maznabili
 
06 Loops
06 Loops06 Loops
06 Loops
maznabili
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statements
maznabili
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-
maznabili
 

More from maznabili (20)

22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solving
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii
 
21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-i
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexity
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
 
15 Text files
15 Text files15 Text files
15 Text files
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
 
12 Exceptions handling
12 Exceptions handling12 Exceptions handling
12 Exceptions handling
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
10 Recursion
10 Recursion10 Recursion
10 Recursion
 
09 Methods
09 Methods09 Methods
09 Methods
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systems
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
06 Loops
06 Loops06 Loops
06 Loops
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statements
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-
 

Recently uploaded

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 

Recently uploaded (20)

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 

02 Primitive data types and variables

  • 1. Primitive Data Types andVariables Creating and RunningYour First C# Program Svetlin Nakov Telerik Corporation www.telerik.com
  • 2. Table of Contents 1. Primitive DataTypes  Integer  Floating-Point / Decimal Floating-Point  Boolean  Character  String  Object 2. Declaring and UsingVariables  Identifiers  DeclaringVariables and AssigningValues  Literals 3. Nullable types 2
  • 4. How Computing Works? Computers are machines that process data  Data is stored in the computer memory in variables  Variables have name, data type and value Example of variable definition and assignment in C# int count = 5; Data type Variable name Variable value 4
  • 5. What Is a DataType? A data type: Is a domain of values of similar characteristics Defines the type of information stored in the computer memory (in a variable) Examples: Positive integers: 1, 2, 3, … Alphabetical characters: a, b, c, … Days of week: Monday, Tuesday, … 5
  • 6. DataType Characteristics A data type has: Name (C# keyword or .NET type) Size (how much memory is used) Default value Example: Integer numbers in C# Name: int Size: 32 bits (4 bytes) Default value: 0 6
  • 8. What are IntegerTypes? Integer types: Represent whole numbers May be signed or unsigned Have range of values, depending on the size of memory used The default value of integer types is: 0 – for integer types, except 0L – for the long type 8
  • 9. IntegerTypes Integer types are: sbyte (-128 to 127): signed 8-bit byte (0 to 255): unsigned 8-bit short (-32,768 to 32,767): signed 16-bit ushort (0 to 65,535): unsigned 16-bit int (-2,147,483,648 to 2,147,483,647): signed 32-bit uint (0 to 4,294,967,295): unsigned 32-bit 9
  • 10. IntegerTypes (2) More integer types: long (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807): signed 64-bit ulong (0 to 18,446,744,073,709,551,615): unsigned 64-bit 10
  • 11. MeasuringTime – Example Depending on the unit of measure we may use different data types: byte centuries = 20; // Usually a small number ushort years = 2000; uint days = 730480; ulong hours = 17531520; // May be a very big number Console.WriteLine("{0} centuries is {1} years, or {2} days, or {3} hours.", centuries, years, days, hours); 11
  • 14. What are Floating-PointTypes? Floating-point types: Represent real numbers May be signed or unsigned Have range of values and different precision depending on the used memory Can behave abnormally in the calculations 14
  • 15. Floating-Point Types Floating-point types are: float (±1.5 × 10−45 to ±3.4 × 1038): 32-bits, precision of 7 digits double (±5.0 × 10−324 to ±1.7 × 10308): 64-bits, precision of 15-16 digits The default value of floating-point types: Is 0.0F for the float type Is 0.0D for the double type 15
  • 16. PI Precision – Example See below the difference in precision when using float and double: NOTE:The “f” suffix in the first statement!  Real numbers are by default interpreted as double!  One should explicitly convert them to float float floatPI = 3.141592653589793238f; double doublePI = 3.141592653589793238; Console.WriteLine("Float PI is: {0}", floatPI); Console.WriteLine("Double PI is: {0}", doublePI); 16
  • 17. Abnormalities in the Floating-Point Calculations Sometimes abnormalities can be observed when using floating-point numbers Comparing floating-point numbers can not be performed directly with the == operator Example: double a = 1.0f; double b = 0.33f; double sum = 1.33f; bool equal = (a+b == sum); // False!!! Console.WriteLine("a+b={0} sum={1} equal={2}", a+b, sum, equal); 17
  • 18. Decimal Floating-PointTypes There is a special decimal floating-point real number type in C#: decimal (±1,0 × 10-28 to ±7,9 × 1028): 128-bits, precision of 28-29 digits Used for financial calculations No round-off errors Almost no loss of precision The default value of decimal type is: 0.0M (M is the suffix for decimal numbers) 18
  • 21. The Boolean DataType The Boolean data type: Is declared by the bool keyword Has two possible values: true and false Is useful in logical expressions The default value is false 21
  • 22. BooleanValues – Example Example of boolean variables taking values of true or false: int a = 1; int b = 2; bool greaterAB = (a > b); Console.WriteLine(greaterAB); // False bool equalA1 = (a == 1); Console.WriteLine(equalA1); // True 22
  • 25. The Character DataType The character data type: Represents symbolic information Is declared by the char keyword Gives each symbol a corresponding integer code Has a '0' default value Takes 16 bits of memory (from U+0000 to U+FFFF) 25
  • 26. Characters and Codes The example below shows that every symbol has an its unique Unicode code: char symbol = 'a'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); symbol = 'b'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); symbol = 'A'; Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol); 26
  • 29. The String DataType The string data type: Represents a sequence of characters Is declared by the string keyword Has a default value null (no value) Strings are enclosed in quotes: Strings can be concatenated Using the + operator string s = "Microsoft .NET Framework"; 29
  • 30. Saying Hello – Example Concatenating the two names of a person to obtain his full name: NOTE: a space is missing between the two names!We have to add it manually string firstName = "Ivan"; string lastName = "Ivanov"; Console.WriteLine("Hello, {0}!n", firstName); string fullName = firstName + " " + lastName; Console.WriteLine("Your full name is {0}.", fullName); 30
  • 33. The ObjectType The object type: Is declared by the object keyword Is the base type of all other types Can hold values of any type 33
  • 34. Using Objects Example of an object variable taking different types of data: object dataContainer = 5; Console.Write("The value of dataContainer is: "); Console.WriteLine(dataContainer); dataContainer = "Five"; Console.Write("The value of dataContainer is: "); Console.WriteLine(dataContainer); 34
  • 37. What Is aVariable? A variable is a: Placeholder of information that can usually be changed at run-time Variables allow you to: Store information Retrieve the stored information Manipulate the stored information 37
  • 38. Variable Characteristics A variable has: Name Type (of stored data) Value Example: Name: counter Type: int Value: 5 int counter = 5; 38
  • 40. DeclaringVariables When declaring a variable we: Specify its type Specify its name (called identifier) May give it an initial value The syntax is the following: Example: <data_type> <identifier> [= <initialization>]; int height = 200; 40
  • 41. Identifiers Identifiers may consist of: Letters (Unicode) Digits [0-9] Underscore "_" Identifiers Can begin only with a letter or an underscore Cannot be a C# keyword 41
  • 42. Identifiers (2) Identifiers Should have a descriptive name It is recommended to use only Latin letters Should be neither too long nor too short Note: In C# small letters are considered different than the capital letters (case sensitivity) 42
  • 43. Identifiers – Examples Examples of correct identifiers: Examples of incorrect identifiers: int new; // new is a keyword int 2Pac; // Cannot begin with a digit int New = 2; // Here N is capital int _2Pac; // This identifiers begins with _ string поздрав = "Hello"; // Unicode symbols used // The following is more appropriate: string greeting = "Hello"; int n = 100; // Undescriptive int numberOfClients = 100; // Descriptive // Overdescriptive identifier: int numberOfPrivateClientOfTheFirm = 100; 43
  • 45. AssigningValues Assigning of values to variables Is achieved by the = operator The = operator has Variable identifier on the left Value of the corresponding data type on the right Could be used in a cascade calling, where assigning is done from right to left 45
  • 46. AssigningValues – Examples Assigning values example: int firstValue = 5; int secondValue; int thirdValue; // Using an already declared variable: secondValue = firstValue; // The following cascade calling assigns // 3 to firstValue and then firstValue // to thirdValue, so both variables have // the value 3 as a result: thirdValue = firstValue = 3; // Avoid this! 46
  • 47. Initializing Variables Initializing Is assigning of initial value Must be done before the variable is used! Several ways of initializing: By using the new keyword By using a literal expression By referring to an already initialized variable 47
  • 48. Initialization – Examples Example of some initializations: // The following would assign the default // value of the int type to num: int num = new int(); // num = 0 // This is how we use a literal expression: float heightInMeters = 1.74f; // Here we use an already initialized variable: string greeting = "Hello World!"; string message = greeting; 48
  • 51. What are Literals? Literals are: Representations of values in the source code There are six types of literals Boolean Integer Real Character String The null literal 51
  • 52. Boolean and Integer Literals The boolean literals are: true false The integer literals: Are used for variables of type int, uint, long, and ulong Consist of digits May have a sign (+,-) May be in a hexadecimal format 52
  • 53. Integer Literals Examples of integer literals The '0x' and '0X' prefixes mean a hexadecimal value, e.g. 0xA8F1 The 'u' and 'U' suffixes mean a ulong or uint type, e.g. 12345678U The 'l' and 'L' suffixes mean a long or ulong type, e.g. 9876543L 53
  • 54. Integer Literals – Example Note: the letter ‘l’ is easily confused with the digit ‘1’ so it’s better to use ‘L’!!! // The following variables are // initialized with the same value: int numberInHex = -0x10; int numberInDec = -16; // The following causes an error, because 234u is of type uint int unsignedInt = 234u; // The following causes an error, because 234L is of type long int longInt = 234L; 54
  • 55. Real Literals The real literals: Are used for values of type float, double and decimal May consist of digits, a sign and “.” May be in exponential notation: 6.02e+23 The “f” and “F” suffixes mean float The “d” and “D” suffixes mean double The “m” and “M” suffixes mean decimal The default interpretation is double 55
  • 56. Real Literals – Example Example of incorrect float literal: A correct way to assign floating-point value (using also the exponential format): 56 // The following causes an error // because 12.5 is double by default float realNumber = 12.5; // The following is the correct // way of assigning the value: float realNumber = 12.5f; // This is the same value in exponential format: realNumber = 1.25e+7f;
  • 57. Character Literals The character literals: Are used for values of the char type Consist of two single quotes surrounding the character value: '<value>' The value may be: Symbol The code of the symbol Escaping sequence 57
  • 58. Escaping Sequences Escaping sequences are: Means of presenting a symbol that is usually interpreted otherwise (like ') Means of presenting system symbols (like the new line symbol) Common escaping sequences are:  ' for single quote " for double quote  for backslash n for new line  uXXXX for denoting any other Unicode symbol 58
  • 59. Character Literals – Example Examples of different character literals: char symbol = 'a'; // An ordinary symbol symbol = 'u006F'; // Unicode symbol code in // a hexadecimal format symbol = 'u8449'; // 葉 (Leaf in Traditional Chinese) symbol = '''; // Assigning the single quote symbol symbol = ''; // Assigning the backslash symbol symbol = 'n'; // Assigning new line symbol symbol = 't'; // Assigning TAB symbol symbol = "a"; // Incorrect: use single quotes 59
  • 60. String Literals String literals: Are used for values of the string type Consist of two double quotes surrounding the value: "<value>" May have a @ prefix which ignores the used escaping sequences: @"<value>" The value is a sequence of character literals string s = "I am a sting literal"; 60
  • 61. String Literals – Example Benefits of quoted strings (the @ prefix): In quoted strings " is used instead of ""! // Here is a string literal using escape sequences string quotation = ""Hello, Jude", he said."; string path = "C:WINNTDartsDarts.exe"; // Here is an example of the usage of @ quotation = @"""Hello, Jimmy!"", she answered."; path = @"C:WINNTDartsDarts.exe"; string str = @"some text"; 61
  • 64. NullableTypes Nullable types are instances of the System.Nullable struct Wrapper over the primitive types E.g. int?, double?, etc. Nullabe type can represent the normal range of values for its underlying value type, plus an additional null value Useful when dealing with Databases or other structures that have default value null
  • 65. NullableTypes – Example int? someInteger = null; Console.WriteLine( "This is the integer with Null value -> " + someInteger); someInteger = 5; Console.WriteLine( "This is the integer with value 5 -> " + someInteger); double? someDouble = null; Console.WriteLine( "This is the real number with Null value -> " + someDouble); someDouble = 2.5; Console.WriteLine( "This is the real number with value 5 -> " + someDouble); Example with Integer: Example with Double:
  • 68. Exercises 1. Declare five variables choosing for each of them the most appropriate of the types byte, sbyte, short, ushort, int, uint, long, ulong to represent the following values: 52130, -115, 4825932, 97, -10000. 2. Which of the following values can be assigned to a variable of type float and which to a variable of type double: 34.567839023, 12.345, 8923.1234857, 3456.091? 3. Write a program that safely compares floating-point numbers with precision of 0.000001. 68
  • 69. Exercises (2) 4. Declare an integer variable and assign it with the value 254 in hexadecimal format. Use Windows Calculator to find its hexadecimal representation. 5. Declare a character variable and assign it with the symbol that has Unicode code 72. Hint: first use the Windows Calculator to find the hexadecimal representation of 72. 6. Declare a boolean variable called isFemale and assign an appropriate value corresponding to your gender. 69
  • 70. Exercises (3) 7. Declare two string variables and assign them with “Hello” and “World”. Declare an object variable and assign it with the concatenation of the first two variables (mind adding an interval). Declare a third string variable and initialize it with the value of the object variable (you should perform type casting). 8. Declare two string variables and assign them with following value: Do the above in two different ways: with and without using quoted strings. The "use" of quotations causes difficulties. 70
  • 71. Exercises (4) 9. Write a program that prints an isosceles triangle of 9 copyright symbols ©. Use Windows Character Map to find the Unicode code of the © symbol. 10. A marketing firm wants to keep record of its employees. Each record would have the following characteristics – first name, family name, age, gender (m or f), ID number, unique employee number (27560000 to 27569999). Declare the variables needed to keep the information for a single employee using appropriate data types and descriptive names. 11. Declare two integer variables and assign them with 5 and 10 and after that exchange their values. 71

Editor's Notes

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  2. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  3. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  4. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  5. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  6. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  7. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  8. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  9. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  10. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  11. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  12. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  13. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  14. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*