Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 42

Literal, Variables and Data

Types
Prof. M Nataraja Suresh
Introduction
• A class is defined 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 ● Identifiers ● Literals
• ● Operators ● Punctuators
Keywords
• Keywords do implement specific features of the language.
• They are reserved, and cannot be used as identifiers except when
they are prefaced by the @ character.
Keywords
• Keywords do implement specific features of the language.
• They are reserved, and cannot be used as identifiers except when
they are prefaced by the @ character.
Identifiers and Literals
• 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.
Operators, Punctuators and Statements
● The Operators are symbols used in expressions to describe
operations involving one or more operands.
Punctuators are symbols used for grouping and separating code. They
define the shape and function of a program. Punctuators (also known
as separators) in C# include:
● Parentheses ( ) ● Colon :
● Braces { } ● Comma ,
● Brackets [ ] ● Period .
● Semicolon ;
Operators, Punctuators and Statements
Statements in C# are like sentences in natural languages. A statement is
an executable combination of tokens ending with a semicolon. C#
implements several types of statements. They include:
● Empty statements ● Jump statements
● Labeled statements ● The try statements
● Declaration statements ● The checked statements
● Expression statements ● The unchecked statements
● Selection statements ● The lock statements
● Interaction statements ● The using statements
Identifier Example
Literals
• Literals are value constants assigned to variables
Literals
• Integer Literals – It refers to a sequence of digits. Could be decimal
integers and hexadecimal integers.
• Decimal integers consist of a set of digits, 0 through 9, preceded by an
optional minus sign. 452, -845, 0
• A sequence of digits preceded by 0x or 0X is considered as a
hexadecimal integer (hex integer). 0X2, 0X3AB
• 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. 0.05632, -.42, .845, 78.56
Literals
• A real literal may also be expressed in exponential (or scientific)
notation. For example, the value 215.65 may be written as 2.1565e2
in exponential notation. e2 means multiply by 102.
• The general form is: mantissa e exponent
• The mantissa is either a real number expressed in decimal notation or
an integer.
• The exponent is an integer with an optional plus or minus sign.
• The letter ‘e’ separating the mantissa and the exponent can be
written in either lowercase or uppercase.
• Since the exponent causes the decimal point to ‘float’, this notation is
said to represent a real number in floating-point form.
• 0.65e4, 3.18E3, 1.5e+5, 12e-2, -1.2E-1
Literals
• Boolean Literals - used as values of relational expressions, a Boolean
literal value can be True / False
• Single Char Literals - single character enclosed within a pair of single
quote marks. ‘4’, ‘D’. ‘-’, ‘ ‘(Space)
• String Literals - string literal is a sequence of characters enclosed between
double quotes. The characters may be alphabets, digits, special characters
and blank spaces
“D”, “Nataraja Suresh”, “N.B.K.R”, “Are you There?”
• Backslash Character Literal - backslash character constants that are used
in output methods
• each one represents one character, although they consist of two
characters.
• These character combinations are known as escape sequences.
Literals
Literals
Literals
• https://docs.microsoft.com/en-us/dotnet/api/system.console.writelin
e?view=net-5.0#:~:text=string%5B%5D%20lines%20%3D%20%7B%20
%22This,string%20line%20in%20lines)%20Console
.
• Visit Above page for good Example
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.
Ex: listSorted_By_Name, avg_Height, waterGlassState
Data Types
• Every variable in C# is associated with a data type.
• 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 divided into (1) Value Types (2) Reference Types
• Difference: Where they are stored in the memory, How they behave in
the context of assignment statements
• Value types (which are of fixed length) are stored on the stack, and when
a value of a variable is assigned to another variable, the value is actually
copied.
• This means that two identical copies of the value are available in memory.
Data Types
• Reference types (which are of variable length) are stored on the heap,
and when an assignment between two reference variables occurs,
only the reference is copied;
• The actual value remains in the same memory location. This means
that there are two references to a single value.
• A third category of types called pointers is available for use only in
unsafe code
Data Types
Value Types
• Predefined value types which are also known as simple types (or
primitive types) are further subdivided into:
● Numeric types,
● Boolean types, and
● Character types.
• Integral types can hold whole numbers such
as 123, –96 and 5639.
Integers

• C# supports the concept of unsigned types (Along with Signed) and


therefore it supports eight types of integers
Signed Integers

• wider data types require more time for manipulation and therefore it
is advisable to use smaller data types wherever possible.
• For example, instead of storing a number like 50 in an int type
variable, we must use a sbyte variable to handle this number
Signed 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
Floating Point Type
• floating-point type to hold numbers containing fractional parts such
as 27.59 and –1.375.
• Float and Double are two kinds of floating point storage in C#
• The float type values are single-precision numbers with a precision of
seven digits.
• The double types represent doubleprecision numbers with a precision
of 15/16 digits
Floating Point Type
• Floating-point numbers, by default, as double-precision quantities.
• To force them to be in single-precision mode, we must append f or F
to the numbers.
Example: 1.23f, 7.56923e5F
• Double-precision types are used when we need greater precision in
storage of floating-point numbers.
• Floating-point data types support a special value known as Not-a-
Number (NaN).
• NaN is used to represent the result of operations such as dividing zero
by zero, where an actual number is not produced.
• Most operations that have NaN as an operand will produce NaN as a
result.
Decimal Types
• The decimal type is a high precision, 128-bit( 16-Byte) data type that
is designed for use in financial and monetary calculations.
• It can store values in the range 1.0 X 10–28 to 7.9 X 1028 with 28
significant digits.
• Note that the precision is given in digits, not in decimal places.
• To specify a number to be decimal type, we must append the
character M (or m) to the value, like 123.45M.
• If we omit M, the value will be treated as double.
Charater Types
• 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 Types
• 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.
• Boolean type is denoted by the keyword bool and uses only one bit of
storage.
• In contrast to C and C++, in C#, we cannot use zero for false and non-
zero for true.
• No conversion between bool type and other integer types is possible.
• All comparison operators return Boolean type values.
• Boolean values are often used in selection and iteration statements.
Reference Types
• 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
predefined types.
They include: ● Classes ● Delegates● Interfaces ● Arrays
• Predefined reference types include two data types:
● Object type ● String type
• The object type is the ultimate base type of all other intrinsic and user-defined
types in C#.
• We can use an object reference to bind to an object of any particular type
• C# provides its own string type for creating and manipulating strings. String
literals discussed earlier can be stored in string objects as values.
• We can perform a number of operations such as copying, comparing and
concatenation on these string objects.
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 about the variable name.
2. It specifies what type of data the variable will hold.
3. The place of declaration decides the scope of the variable.
• A variable must be declared before it is used in the program.
• C# allows any properly formed variable to have any declared data type.
• The declaration statement defines the type of variable. The general
form of declaration of a variable is
type variable1, variable2, variableN;
Default value of Variables

Static variables, Instance


variables, Array elements
are automatically
initialized to their default
values
Constants
• 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.
const int ROWS = 10;
const int COLS = 20;
const int NUM = 90;
• Such variables can be made unmodifiable by using the const keyword
while initializing them.
• constants must be declared and initialized simultaneously. For Ex,
Const myConst;
myConst=10;
is illegal
Constants
• we cannot use non-const values in expressions
int myVar=10;
const int myConst = 15 + myVar; // Illegal
Why Constants?
●They make our programs easier to read and understand.
● They make our programs easier to modify.
● They minimize accidental errors, like attempting to assign values to some
variables which are expected to be constants.
Scope of Variables
• The scope of a variable is the region of code within which the variable
is accessible.
• 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
Scope of Variables

m - static variable
n - instance variable
x - value parameter
y - reference parameter
z - output parameter
a[0] - an array element
J - a local variable
Scope of Variables
• 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.
• The variables x, y and z are parameters of the method fun( ).
• The value parameter x will exist till the end of the method.
• The reference and output parameters ( y and z ) do not create new storage
locations. Instead, they represent the same storage locations as the
variables that are passed as arguments.
• The scope of these variables is always the same as the underlying-variables.
• The elements of an array such as a[0] come into existence when an array
instance is created, and cease to exist when there are no references to that
array instance. Arrays declared at class level behave like fields
Scope of Variables
• Variables declared inside methods are called local variables. They are
called so because they are not available for use outside the method
definition.
• Local variables can also be declared inside program blocks that are
defined between an opening brace { and a closing brace }.
• The scope of a local variable starts immediately after its identifier in
the declaration and extends up to the end of the block containing the
declaration.
• Within the scope of a local variable, it is an error to declare another
local variable with the same name
Scope of Variables
Field Variables (Class) Vs Local Variables(Methods)
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 means the conversion of a value type on the stack to an object
type on the heap.
• Conversely, the conversion from an object type back to a value type is
known as unboxing.

creates a temporary reference_type ‘box’ for the object on heap. We can also use a
C-style cast for boxing
Boxing and Unboxing
• boxing operation creates a copy of the value of the m integer to the
object om, which resides on the heap.
• This means that the values are independent of each other.
• In the following code the value of m changes, while the value of om is not
affected
Boxing and Unboxing
• Unboxing

• When unboxing a value, we have to ensure that the value type is large
enough to hold the value of the object. For example, the following
code will produce a runtime error

You might also like