SlideShare a Scribd company logo
@ 2010 Tata McGraw-Hill Education
1
Education
Literals, Variables and Data TypesLiterals, Variables and Data Types
@ 2010 Tata McGraw-Hill Education
2
Education
Introduction
A C# program is basically a collection of classes. A class is defi ned by a set
of declaration statements and methods containing instructions known as
executable statements. These instructions are formed using certain
symbols and words according to some rigid rules known as syntax rules (or
grammar). The smallest, non-reducible, textual elements in a program are
referred to as tokens. The compiler recognizes them for building up
expressions and statements. In simple terms, a C# program is a collection of
tokens, comments and white spaces. C# includes the following five types of
tokens:Keywords
Operators
 Identifiers
Punctuators
Literals
White spaces and comments are not tokens, though they may act as
separators for tokens. Keywords are an essential part of a language defi
nition. They implement specific features of the language. They are
reserved, and cannot be used as identifiers except when they are prefaced
by the @ character
@ 2010 Tata McGraw-Hill Education
3
Education
Identifiers are programmer-designed tokens. They are used for naming
classes, methods, variables, labels, namespaces, interfaces, etc. C# identifiers
enforce the following rules:
They can have alphabets, digits and underscore characters
They must not begin with a digit
Upper case and lower case letters are distinct
Keywords in stand-alone mode cannot be used as identifiers
Literals are the way in which the values that are stored in variables are
represented. We shall discuss these in detail in the next section
@ 2010 Tata McGraw-Hill Education
4
Education
Operators are symbols used in expressions to describe operations involving
one or more operands. Operators are considered in detail in Chapter 5.
Punctuators are symbols used for grouping and separating code. They defi
ne the shape and function of a program. Punctuators (also known as
separators) in C# include:
Parentheses ( )
Braces { }
Brackets [ ]
Semicolons ;
Colon:
Comma ,
Period .
@ 2010 Tata McGraw-Hill Education
5
Education
LITERALS
Literals are value constants assigned to variables (or results of expressions) in a
program. C# supports several types of literals as illustrated in Fig. 4.1.
@ 2010 Tata McGraw-Hill Education
6
Education
Integer Literals
An integer literal refers to a sequence of digits. There are two types of integers,
namely, decimal integers and hexadecimal integers.
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional minus
sign. Valid examples of decimal integer literals are:
123 -321 0 654321
Embedded spaces, commas and non-digit characters are not permitted between digits.
For example, 15 750 20,000 $1000 are illegal numbers.
A sequence of digits preceded by 0x or 0X is considered as a hexadecimal integer (hex
integer). It may also include alphabets A through F or ‘a’ through ‘f’. A letter A
through F represents the numbers 10 through 15. Following are the examples of valid
hex integers. 0X2 0X9F 0Xbcd 0x
@ 2010 Tata McGraw-Hill Education
7
Education
Real Literals
Integer literals are inadequate to represent quantities that vary continuously, such as
distances, heights, temperatures, prices and so on. These quantities are represented by
numbers containing fractional parts like 17.548. Such numbers are called real (or
floating point) numbers. Further examples of real literals are:
0.0083 -0.75 435.36
These numbers are shown in decimal notation, having a whole number followed by a
decimal point and the fractional part, which is an integer. It is possible that the number
may not have digits before the decimal point, or digits after the decimal point. That is,
215. .95 -.71 are all valid real literals.
Boolean Literals
There are two Boolean literal values:
True False
They are used as values of relational expressions.
@ 2010 Tata McGraw-Hill Education
8
Education
Single Character Literals
A single-character literal (or simply character constant) contains a single character
enclosed within a pair of single quote marks. Example of character in the examples
above constants are:
‘5’ ‘X’ ‘;’ ‘ ‘
Note that the character constant ‘5’ is not the same as the number 5. The last constant in
the example above is a blank space.
String Literals
A string literal is a sequence of characters enclosed between double quotes.The
characters may be alphabets, digits, special characters and blank spaces. Examples
are:
“Hello C#” “2001” “WELL DONE” “?...!” “5+3” “X”
@ 2010 Tata McGraw-Hill Education
9
Education
Backslash Character Literal
C# supports some special backslash character constants that are used in output methods.
For example, the symbol ‘n’ stands for a new-line character. A list of such backslash
character literals is given in Table 4.2. Note that each one
represents one character, although they consist of two characters. These character
combinations are known as escape sequences.
@ 2010 Tata McGraw-Hill Education
10
Education
Program 4.2 prints the various numeric literals available in C#, such as Integer,
Double and Exponential.
@ 2010 Tata McGraw-Hill Education
11
Education
VARIABLES
A variable is an identifier that denotes a storage location used to store a data value.
Unlike constants that remain unchanged during the execution of a program, a variable
may take different values at different times during the execution of the program.
Every variable has a type that determines what values can
be stored in the variable. A variable name can be chosen by the programmer in a
meaningful way so as to reflect what it represents in the program. Some examples of
variable names are:
average
height
total_height
Class Strength
@ 2010 Tata McGraw-Hill Education
12
Education
As mentioned earlier, variable names may consist of alphabets, digits and the
underscore ( _ ), subject to the following conditions:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct. This means that the variable Total is
not the same as total or TOTAL.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable names can be of any length.
@ 2010 Tata McGraw-Hill Education
13
Education
DATA TYPES
Data types specify the size and type of values that can be stored. C# is a language rich
in its data types. The variety available allows the programmer to
select the type appropriate to the needs of the application. The types in C# are
primarily divided into two categories:
Value types
Reference types
Value types and reference types differ in two characteristics:
Where they are stored in the memory
How they behave in the context of assignment statements
@ 2010 Tata McGraw-Hill Education
14
Education
@ 2010 Tata McGraw-Hill Education
15
Education
VALUE TYPES
The value types of C# can be grouped into two categories (as shown in Fig. 4.2),
namely,
User-defined types (or complex types) and
Predefined types (or simple types)
We can define our own complex types known as user-defined value types which
include struct types and enumerations. They are discussed in Chapter 11. Predefined
value types which are also known as simple types (or primitive types) are further
subdivided into:
Numeric types,
Boolean types, and
Character types.
@ 2010 Tata McGraw-Hill Education
16
Education
Note: C# 2.0 added a new type
called nullable type. This type
variable can hold an undefined value
Any value type variable can be defined
as a nullable type.
@ 2010 Tata McGraw-Hill Education
17
Education
Integral Types
Integral types can hold whole numbers such as 123, –96 and 5639. The size of the
values that can be stored depends on the integral data type we choose. C# supports the
concept of unsigned types and therefore it supports eight types of integers as shown in
Figs 4.4 and 4.5.
@ 2010 Tata McGraw-Hill Education
18
Education
Signed Integers
Signed integer types can hold both positive and negative numbers. Table 4.3 shows
the memory size and range of all the four signed integer data types.(Note that one byte
is equal to eight bits).
@ 2010 Tata McGraw-Hill Education
19
Education
Unsigned Integers
We can increase the size of the positive value stored in an integer type by making it
‘unsigned’. For example, a 16-bit short integer can store values in the range –32,768 to
32,767. However, by making it ushort, it can handle values in the range 0 to 65,535.
Table 4.4 shows the size and range of all the four unsigned integer data types.
@ 2010 Tata McGraw-Hill Education
20
Education
Floating-Point Types
Integer types can hold only whole numbers and therefore we use another type known
as fl oating-point type to hold numbers containing fractional parts such as 27.59 and –
1.375. There are two kinds of fl oating point storage in C#
as shown in Fig. 4.6.
@ 2010 Tata McGraw-Hill Education
21
Education
Decimal Type
The decimal type is a high precision, 128-bit data type that is designed for use in
financial and monetary calculations. It can store values in the range 1.0 ∞ 10–28 to 7.9
∞ 1028 with 28 significant digits. Note that the precision is given in digits, not in
decimal places.
Character Type
In order to store single characters in memory, C# provides a character data type called
char. The char type assumes a size of two bytes but, in fact it can hold only a single
character. It has been designed to hold a 16-bit Unicode character, in which the 8-bit
ASCII code is a subset.
Boolean Type
Boolean type is used when we want to test a particular condition during the execution
of the program. There are only two values that a Boolean type can take: true or
false. Remember, both these words have been declared as keywords.
@ 2010 Tata McGraw-Hill Education
22
Education
REFERENCE TYPES
As with value types, the reference types can also be divided into two groups:
User-defined (or complex types)
Predefined (or simple types)
User-defined reference types refer to those types which we define using predefi ned
types. They include:
Classes
Delegates
Interfaces
Arrays
These complex types will be discussed in later chapters when we take up these topics
individually. Predefined reference types include two data types:
Object type String type
@ 2010 Tata McGraw-Hill Education
23
Education
DECLARATION OF VARIABLES
Variables are the names of storage locations. After designing suitable variable names,
we must declare them to the compiler. Declaration does three things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. The place of declaration (in the program) decides the scope of the variable.
A variable must be declared before it is used in the program.
The general form of declaration of a variable is:
type Variable1, Variable2, ……VariableN;
Variables are separated by commas, A declaration statement must end with a
semicolon.
@ 2010 Tata McGraw-Hill Education
24
Education
INITIALIZATION OF VARIABLES
A variable must be given a value after it has been declared but before it is used in an
expression. A simple method of giving value to a variable is through the assignment
statement as follows: variableName = value;
Examples:
initial Value = O;
final Value = 100;
yes = ‘x’;
DEFAULT VALUES
A variable is either explicitly assigned a value or automatically assigned a default
value. The following categories of variables are automatically initialized to their
default values:
Static variables Instance variables Array elements
@ 2010 Tata McGraw-Hill Education
25
Education
@ 2010 Tata McGraw-Hill Education
26
Education
CONSTANT VARIABLES
The variables whose values do not change during the execution of a program are
known as constants. For example, the variables representing the maximum number of
rows and columns of a matrix or number of students in a class in a program may not
change during execution of the program. Such variables can be made unmodifiable by
using the const keyword while initializing them.
Example:
const int ROWS = 10;
const int COLS = 20;
const int NUM = 90
@ 2010 Tata McGraw-Hill Education
27
Education
SCOPE OF VARIABLES
The scope of a variable is the region of code within which the variable can be
accessed. This depends on the type of the variable and place of its declaration. C#
defines several categories of variables. They include:
Static variables
Instance variables
Array elements
Value parameters
Reference parameters
Output parameters
Local variables
@ 2010 Tata McGraw-Hill Education
28
Education
This code contains the following variables:
m as a static variable
n as an instance variable
x as a value parameter
y as a reference parameter
z as an output parameter
a[0] as an array element
j as a local variable
Static and instance variables are declared at the class level and are known as fields or
field variables. The scope of these variables begins at the place of their declaration
and ends when the Main method terminates.
@ 2010 Tata McGraw-Hill Education
29
Education
BOXING AND UNBOXING
In object-oriented programming, methods are invoked using objects. Since value types
such as int and long are not objects, we cannot use them to call methods. C# enables
us to achieve this through a technique known as boxing .
Boxing
Any type, value or reference can be assigned to an object without an explicit
conversion. When the compiler finds a value type where it needs a reference type, it
creates an object ‘box’ into which it places the value of the value type. The following
code illustrates boxing:
int m = 100;
object om = m; // creates a box to hold m
When executed, this code creates a temporary reference_type ‘box’ for the object on
heap. We can also use a C-style cast for boxing.
int m = 100;
object om = m; // creates a box to hold m
@ 2010 Tata McGraw-Hill Education
30
Education
Unboxing
Unboxing is the process of converting the object type back to the value type.
Remember that we can only unbox a variable that has previously been boxed. In
contrast to boxing, unboxing is an explicit operation using C-style casting
int m = 10;
object om = m; //box m
int n = (int)om; //unbox om back to an int
When unboxing a value, we have to ensure that the value type is large enough to hold
the value of the object. Otherwise, the operation may result in a runtime error. For
example, the code
int m = 500;
object om = m;
byte n = (byte)om;

More Related Content

PPTX
classes and objects in C++
PDF
Function overloading ppt
PPT
friend function(c++)
PPTX
This pointer
PPTX
PPTX
class and objects
PPTX
C# classes objects
PPTX
Types of Constructor in C++
classes and objects in C++
Function overloading ppt
friend function(c++)
This pointer
class and objects
C# classes objects
Types of Constructor in C++

What's hot (20)

PPT
OOP in C++
PPTX
User defined functions in C
PPTX
Friend function
PPTX
Virtual base class
PDF
Java variable types
DOCX
Abstraction in c++ and Real Life Example of Abstraction in C++
PPTX
Inheritance in c++
PPTX
Data types in java
PPTX
Type casting in java
PPTX
Abstract class in c++
PPT
Class and object in c++
PPTX
07. Virtual Functions
PPTX
Java- Nested Classes
PPTX
Constructors in C++
PPTX
Virtual function in C++ Pure Virtual Function
PPTX
INLINE FUNCTION IN C++
PDF
Constructor and Destructor
PPTX
Static Data Members and Member Functions
PPTX
Multiple inheritance possible in Java
PPT
Java inheritance
OOP in C++
User defined functions in C
Friend function
Virtual base class
Java variable types
Abstraction in c++ and Real Life Example of Abstraction in C++
Inheritance in c++
Data types in java
Type casting in java
Abstract class in c++
Class and object in c++
07. Virtual Functions
Java- Nested Classes
Constructors in C++
Virtual function in C++ Pure Virtual Function
INLINE FUNCTION IN C++
Constructor and Destructor
Static Data Members and Member Functions
Multiple inheritance possible in Java
Java inheritance
Ad

Similar to Literals,variables,datatype in C# (20)

PPTX
Module 1:Introduction
DOC
Data type
PDF
PSPC--UNIT-2.pdf
PDF
Constants Variables Datatypes by Mrs. Sowmya Jyothi
PPTX
PPTX
Fundamentals of C Programming Language
PPTX
C# lecture 2: Literals , Variables and Data Types in C#
PPTX
PROGRAMMING IN C - Inroduction.pptx
PPT
C the basic concepts
DOCX
Dot net programming concept
PDF
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
PPTX
C tokens
PPTX
programming for problem solving in C and C++.pptx
PPT
Basics of C.ppt
PPTX
Data Types and Variables In C Programming
PDF
Basic of the C language
PPTX
Data Types, Variables, and Constants in C# Programming
PPT
Basics of c
PPTX
Structure of c_program_to_input_output
PPTX
Aniket tore
Module 1:Introduction
Data type
PSPC--UNIT-2.pdf
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Fundamentals of C Programming Language
C# lecture 2: Literals , Variables and Data Types in C#
PROGRAMMING IN C - Inroduction.pptx
C the basic concepts
Dot net programming concept
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
C tokens
programming for problem solving in C and C++.pptx
Basics of C.ppt
Data Types and Variables In C Programming
Basic of the C language
Data Types, Variables, and Constants in C# Programming
Basics of c
Structure of c_program_to_input_output
Aniket tore
Ad

More from Prasanna Kumar SM (8)

PPT
C# Introduction brief
PPT
Structure and Enum in c#
PPT
Overview of c#
PPT
Operators and Expressions in C#
PPT
Methods in C#
PPT
Decision making and loop in C#
PPT
Characteristics of c#
PPT
C# Introduction brief
Structure and Enum in c#
Overview of c#
Operators and Expressions in C#
Methods in C#
Decision making and loop in C#
Characteristics of c#

Recently uploaded (20)

PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Cell Structure & Organelles in detailed.
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
Updated Idioms and Phrasal Verbs in English subject
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
RMMM.pdf make it easy to upload and study
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Classroom Observation Tools for Teachers
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Lesson notes of climatology university.
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
Computing-Curriculum for Schools in Ghana
Chinmaya Tiranga quiz Grand Finale.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
Microbial diseases, their pathogenesis and prophylaxis
Cell Structure & Organelles in detailed.
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Updated Idioms and Phrasal Verbs in English subject
Supply Chain Operations Speaking Notes -ICLT Program
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
LDMMIA Reiki Yoga Finals Review Spring Summer
Final Presentation General Medicine 03-08-2024.pptx
RMMM.pdf make it easy to upload and study
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Microbial disease of the cardiovascular and lymphatic systems
Classroom Observation Tools for Teachers
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Lesson notes of climatology university.
History, Philosophy and sociology of education (1).pptx
Computing-Curriculum for Schools in Ghana

Literals,variables,datatype in C#

  • 1. @ 2010 Tata McGraw-Hill Education 1 Education Literals, Variables and Data TypesLiterals, Variables and Data Types
  • 2. @ 2010 Tata McGraw-Hill Education 2 Education Introduction A C# program is basically a collection of classes. A class is defi ned by a set of declaration statements and methods containing instructions known as executable statements. These instructions are formed using certain symbols and words according to some rigid rules known as syntax rules (or grammar). The smallest, non-reducible, textual elements in a program are referred to as tokens. The compiler recognizes them for building up expressions and statements. In simple terms, a C# program is a collection of tokens, comments and white spaces. C# includes the following five types of tokens:Keywords Operators  Identifiers Punctuators Literals White spaces and comments are not tokens, though they may act as separators for tokens. Keywords are an essential part of a language defi nition. They implement specific features of the language. They are reserved, and cannot be used as identifiers except when they are prefaced by the @ character
  • 3. @ 2010 Tata McGraw-Hill Education 3 Education Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, labels, namespaces, interfaces, etc. C# identifiers enforce the following rules: They can have alphabets, digits and underscore characters They must not begin with a digit Upper case and lower case letters are distinct Keywords in stand-alone mode cannot be used as identifiers Literals are the way in which the values that are stored in variables are represented. We shall discuss these in detail in the next section
  • 4. @ 2010 Tata McGraw-Hill Education 4 Education Operators are symbols used in expressions to describe operations involving one or more operands. Operators are considered in detail in Chapter 5. Punctuators are symbols used for grouping and separating code. They defi ne the shape and function of a program. Punctuators (also known as separators) in C# include: Parentheses ( ) Braces { } Brackets [ ] Semicolons ; Colon: Comma , Period .
  • 5. @ 2010 Tata McGraw-Hill Education 5 Education LITERALS Literals are value constants assigned to variables (or results of expressions) in a program. C# supports several types of literals as illustrated in Fig. 4.1.
  • 6. @ 2010 Tata McGraw-Hill Education 6 Education Integer Literals An integer literal refers to a sequence of digits. There are two types of integers, namely, decimal integers and hexadecimal integers. Decimal integers consist of a set of digits, 0 through 9, preceded by an optional minus sign. Valid examples of decimal integer literals are: 123 -321 0 654321 Embedded spaces, commas and non-digit characters are not permitted between digits. For example, 15 750 20,000 $1000 are illegal numbers. A sequence of digits preceded by 0x or 0X is considered as a hexadecimal integer (hex integer). It may also include alphabets A through F or ‘a’ through ‘f’. A letter A through F represents the numbers 10 through 15. Following are the examples of valid hex integers. 0X2 0X9F 0Xbcd 0x
  • 7. @ 2010 Tata McGraw-Hill Education 7 Education Real Literals Integer literals are inadequate to represent quantities that vary continuously, such as distances, heights, temperatures, prices and so on. These quantities are represented by numbers containing fractional parts like 17.548. Such numbers are called real (or floating point) numbers. Further examples of real literals are: 0.0083 -0.75 435.36 These numbers are shown in decimal notation, having a whole number followed by a decimal point and the fractional part, which is an integer. It is possible that the number may not have digits before the decimal point, or digits after the decimal point. That is, 215. .95 -.71 are all valid real literals. Boolean Literals There are two Boolean literal values: True False They are used as values of relational expressions.
  • 8. @ 2010 Tata McGraw-Hill Education 8 Education Single Character Literals A single-character literal (or simply character constant) contains a single character enclosed within a pair of single quote marks. Example of character in the examples above constants are: ‘5’ ‘X’ ‘;’ ‘ ‘ Note that the character constant ‘5’ is not the same as the number 5. The last constant in the example above is a blank space. String Literals A string literal is a sequence of characters enclosed between double quotes.The characters may be alphabets, digits, special characters and blank spaces. Examples are: “Hello C#” “2001” “WELL DONE” “?...!” “5+3” “X”
  • 9. @ 2010 Tata McGraw-Hill Education 9 Education Backslash Character Literal C# supports some special backslash character constants that are used in output methods. For example, the symbol ‘n’ stands for a new-line character. A list of such backslash character literals is given in Table 4.2. Note that each one represents one character, although they consist of two characters. These character combinations are known as escape sequences.
  • 10. @ 2010 Tata McGraw-Hill Education 10 Education Program 4.2 prints the various numeric literals available in C#, such as Integer, Double and Exponential.
  • 11. @ 2010 Tata McGraw-Hill Education 11 Education VARIABLES A variable is an identifier that denotes a storage location used to store a data value. Unlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program. Every variable has a type that determines what values can be stored in the variable. A variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents in the program. Some examples of variable names are: average height total_height Class Strength
  • 12. @ 2010 Tata McGraw-Hill Education 12 Education As mentioned earlier, variable names may consist of alphabets, digits and the underscore ( _ ), subject to the following conditions: 1. They must not begin with a digit. 2. Uppercase and lowercase are distinct. This means that the variable Total is not the same as total or TOTAL. 3. It should not be a keyword. 4. White space is not allowed. 5. Variable names can be of any length.
  • 13. @ 2010 Tata McGraw-Hill Education 13 Education DATA TYPES Data types specify the size and type of values that can be stored. C# is a language rich in its data types. The variety available allows the programmer to select the type appropriate to the needs of the application. The types in C# are primarily divided into two categories: Value types Reference types Value types and reference types differ in two characteristics: Where they are stored in the memory How they behave in the context of assignment statements
  • 14. @ 2010 Tata McGraw-Hill Education 14 Education
  • 15. @ 2010 Tata McGraw-Hill Education 15 Education VALUE TYPES The value types of C# can be grouped into two categories (as shown in Fig. 4.2), namely, User-defined types (or complex types) and Predefined types (or simple types) We can define our own complex types known as user-defined value types which include struct types and enumerations. They are discussed in Chapter 11. Predefined value types which are also known as simple types (or primitive types) are further subdivided into: Numeric types, Boolean types, and Character types.
  • 16. @ 2010 Tata McGraw-Hill Education 16 Education Note: C# 2.0 added a new type called nullable type. This type variable can hold an undefined value Any value type variable can be defined as a nullable type.
  • 17. @ 2010 Tata McGraw-Hill Education 17 Education Integral Types Integral types can hold whole numbers such as 123, –96 and 5639. The size of the values that can be stored depends on the integral data type we choose. C# supports the concept of unsigned types and therefore it supports eight types of integers as shown in Figs 4.4 and 4.5.
  • 18. @ 2010 Tata McGraw-Hill Education 18 Education Signed Integers Signed integer types can hold both positive and negative numbers. Table 4.3 shows the memory size and range of all the four signed integer data types.(Note that one byte is equal to eight bits).
  • 19. @ 2010 Tata McGraw-Hill Education 19 Education Unsigned Integers We can increase the size of the positive value stored in an integer type by making it ‘unsigned’. For example, a 16-bit short integer can store values in the range –32,768 to 32,767. However, by making it ushort, it can handle values in the range 0 to 65,535. Table 4.4 shows the size and range of all the four unsigned integer data types.
  • 20. @ 2010 Tata McGraw-Hill Education 20 Education Floating-Point Types Integer types can hold only whole numbers and therefore we use another type known as fl oating-point type to hold numbers containing fractional parts such as 27.59 and – 1.375. There are two kinds of fl oating point storage in C# as shown in Fig. 4.6.
  • 21. @ 2010 Tata McGraw-Hill Education 21 Education Decimal Type The decimal type is a high precision, 128-bit data type that is designed for use in financial and monetary calculations. It can store values in the range 1.0 ∞ 10–28 to 7.9 ∞ 1028 with 28 significant digits. Note that the precision is given in digits, not in decimal places. Character Type In order to store single characters in memory, C# provides a character data type called char. The char type assumes a size of two bytes but, in fact it can hold only a single character. It has been designed to hold a 16-bit Unicode character, in which the 8-bit ASCII code is a subset. Boolean Type Boolean type is used when we want to test a particular condition during the execution of the program. There are only two values that a Boolean type can take: true or false. Remember, both these words have been declared as keywords.
  • 22. @ 2010 Tata McGraw-Hill Education 22 Education REFERENCE TYPES As with value types, the reference types can also be divided into two groups: User-defined (or complex types) Predefined (or simple types) User-defined reference types refer to those types which we define using predefi ned types. They include: Classes Delegates Interfaces Arrays These complex types will be discussed in later chapters when we take up these topics individually. Predefined reference types include two data types: Object type String type
  • 23. @ 2010 Tata McGraw-Hill Education 23 Education DECLARATION OF VARIABLES Variables are the names of storage locations. After designing suitable variable names, we must declare them to the compiler. Declaration does three things: 1. It tells the compiler what the variable name is. 2. It specifies what type of data the variable will hold. 3. The place of declaration (in the program) decides the scope of the variable. A variable must be declared before it is used in the program. The general form of declaration of a variable is: type Variable1, Variable2, ……VariableN; Variables are separated by commas, A declaration statement must end with a semicolon.
  • 24. @ 2010 Tata McGraw-Hill Education 24 Education INITIALIZATION OF VARIABLES A variable must be given a value after it has been declared but before it is used in an expression. A simple method of giving value to a variable is through the assignment statement as follows: variableName = value; Examples: initial Value = O; final Value = 100; yes = ‘x’; DEFAULT VALUES A variable is either explicitly assigned a value or automatically assigned a default value. The following categories of variables are automatically initialized to their default values: Static variables Instance variables Array elements
  • 25. @ 2010 Tata McGraw-Hill Education 25 Education
  • 26. @ 2010 Tata McGraw-Hill Education 26 Education CONSTANT VARIABLES The variables whose values do not change during the execution of a program are known as constants. For example, the variables representing the maximum number of rows and columns of a matrix or number of students in a class in a program may not change during execution of the program. Such variables can be made unmodifiable by using the const keyword while initializing them. Example: const int ROWS = 10; const int COLS = 20; const int NUM = 90
  • 27. @ 2010 Tata McGraw-Hill Education 27 Education SCOPE OF VARIABLES The scope of a variable is the region of code within which the variable can be accessed. This depends on the type of the variable and place of its declaration. C# defines several categories of variables. They include: Static variables Instance variables Array elements Value parameters Reference parameters Output parameters Local variables
  • 28. @ 2010 Tata McGraw-Hill Education 28 Education This code contains the following variables: m as a static variable n as an instance variable x as a value parameter y as a reference parameter z as an output parameter a[0] as an array element j as a local variable Static and instance variables are declared at the class level and are known as fields or field variables. The scope of these variables begins at the place of their declaration and ends when the Main method terminates.
  • 29. @ 2010 Tata McGraw-Hill Education 29 Education BOXING AND UNBOXING In object-oriented programming, methods are invoked using objects. Since value types such as int and long are not objects, we cannot use them to call methods. C# enables us to achieve this through a technique known as boxing . Boxing Any type, value or reference can be assigned to an object without an explicit conversion. When the compiler finds a value type where it needs a reference type, it creates an object ‘box’ into which it places the value of the value type. The following code illustrates boxing: int m = 100; object om = m; // creates a box to hold m When executed, this code creates a temporary reference_type ‘box’ for the object on heap. We can also use a C-style cast for boxing. int m = 100; object om = m; // creates a box to hold m
  • 30. @ 2010 Tata McGraw-Hill Education 30 Education Unboxing Unboxing is the process of converting the object type back to the value type. Remember that we can only unbox a variable that has previously been boxed. In contrast to boxing, unboxing is an explicit operation using C-style casting int m = 10; object om = m; //box m int n = (int)om; //unbox om back to an int When unboxing a value, we have to ensure that the value type is large enough to hold the value of the object. Otherwise, the operation may result in a runtime error. For example, the code int m = 500; object om = m; byte n = (byte)om;