0% found this document useful (0 votes)
27 views69 pages

Primitive Types in C#

The document provides an overview of primitive data types and variables in C#, including integer, floating-point, boolean, character, string, and object types. It explains how to declare and use variables, the characteristics of data types, and the importance of choosing appropriate data types for different scenarios. Additionally, it covers literals and their representations in the source code.

Uploaded by

24250155nikesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views69 pages

Primitive Types in C#

The document provides an overview of primitive data types and variables in C#, including integer, floating-point, boolean, character, string, and object types. It explains how to declare and use variables, the characteristics of data types, and the importance of choosing appropriate data types for different scenarios. Additionally, it covers literals and their representations in the source code.

Uploaded by

24250155nikesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Primitive Data

Types and Variables


Integer, Floating-Point, Text
Data, Variables, Literals

Nausheeda B S
Dept of IT
AIMIT
Data Types in C#

C# Data Types

Reference
Value Types Types

User-
Predefined User- Predefined Defined
Types Defined Types Types
Types
Integer Classes
Boolean Enumerations Objects
Strings Arrays
Characters Structures Delegates
Real Numbers etc. Interfaces
Table of Contents
1. Primitive Data Types
 Integer
 Floating-Point / Decimal Floating-Point
 Boolean
 Character
 String
 Object
2. Declaring and Using Variables
 Identifiers, Variables, Literals
3. Nullable Types
3
Primitive Data Types
How Computing Works?
 Computers are machines that process data
 Data is stored in the computer memory in variables

 Variables have data type, name and value

 Example of variable definition and assignment in C#

Variable name
Data type int count = 5;
Variable value

 When processed, data is stored back into variables


5
What Is a Data Type?
 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, …


6
Data Type Characteristics
 A data type has:
 Name (C# keyword or .NET type)
 Size (how much memory is used) int: sequence of 32
bits in the memory
 Default value
 Example:
int: 4 sequential
 Integer numbers in C#
bytes in the memory
 Name: int
 Size: 32 bits (4 bytes)
 Default value: 0
7
Integer Types
What are Integer Types?
 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

9
Integer Types
 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
 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
Measuring Time – Example
 Depending on the unit of measure we may use different data
types:

byte centuries = 20; // A small number (up to 255)


ushort years = 2000; // A small number (up to 32767)
uint days = 730480; // A large number (up to 4.3 billions)
ulong hours = 17531520; // A very big number (up to 18.4*10^18)
Console.WriteLine(
"{0} centuries is {1} years, or {2} days, or {3} hours.",
centuries, years, days, hours);
11
Integer Types
Floating-Point and
Decimal Floating-Point Types
What are Floating-Point Types?
 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
 Difference in precision when using float and double:

float floatPI = 3.141592653589793238f;


double doublePI = 3.141592653589793238;
Console.WriteLine("Float PI is: {0}", floatPI);
Console.WriteLine("Double PI is: {0}", doublePI);

 NOTE: The "f" suffix in the first statement!


 Real numbers are by default interpreted as double!

 One should explicitly convert them to float


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

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-Point Types
 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-Point Types
Boolean Type
The Boolean Data Type
 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
Boolean Values – 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
Boolean Type
Character Type
The Character Data Type
 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)

 Holds a single Unicode character (or part of character)


25
Characters and Codes
 The example below shows that every
character has an 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);
symbol = 'щ'; // Cyrillic letter 'sht'
Console.WriteLine("The code of '{0}' is: {1}", symbol, (int) symbol);

26
Character Type
String Type
The String Data Type
 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:


string s = "Hello, C#";

 Strings can be concatenated


 Using the + operator
29
Saying Hello – Example
 Concatenating the names of a person to obtain the full name:
string firstName = "Ivan";
string lastName = "Ivanov";
Console.WriteLine("Hello, {0}!", firstName);

string fullName = firstName + " " + lastName;


Console.WriteLine("Your full name is {0}.", fullName);

 We can concatenate strings and numbers as well:


int age = 21;
Console.WriteLine("Hello, I am " + age + " years old");
30
String Type
Object Type
The Object Type
 The object type:
 Is declared by the object keyword
 Is the base type of all other types
 Can hold values of any type

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);
33
Objects
Most Appropriate Data Types
 Determine the most appropriate data types:
 Person age→ byte
 Number of colors (16 million) → int
 Bank account balance → decimal
 First name → string
 Food price → double
 Distance between the Sun and Neptune in km → long
 Copyright symbol © → char
 Check if two names are equal → bool
Introducing Variables
What Is a Variable?
 Variables keep data in the computer memory
 A variable is a:
 Placeholder of information that can be changed at run-time

 Variables allow you to:


 Store information

 Retrieve the stored information

 Change the stored information

37
Variable Characteristics
 A variable has:
 Name
 Type (of stored data)
 Value
 Example:
int counter = 5;

 Name: counter
 Type: int
 Value: 5
38
Declaring and Using Variables
Declaring Variables
 When declaring a variable we:
 Specify its type

 Specify its name (called identifier)

 May give it an initial value

 The syntax is the following:


<data_type> <identifier> [= <initialization>];

 Example:
int height = 200;
40
Identifiers
 Identifiers may consist of:
 Letters (Unicode)

 Digits [0-9]

 Underscore "_"

 Examples: count, firstName, Page


 Identifiers
 Can begin only with a letter or an underscore

 Cannot be a C# keyword (like int and class)


41
Identifiers (2)
 Identifiers
 Should have a descriptive name
 E.g. firstName, not dasfas or p17
 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 syntactically correct identifiers:
int New = 2; // here N is capital
int _2Pac; // this identifiers begins with underscore _
string поздрав = "Hello"; // Unicode symbols are acceptable
string greeting = "Hello"; // more appropriate name
int n = 100; // undescriptive
int numberOfClients = 100; // good, descriptive name
int numberOfPrivateClientOfTheFirm = 100; // overdescriptive

 Examples of syntactically incorrect identifiers:


int new; // new is a keyword
int 2Pac; // cannot begin with a digit
43
Assigning Values
To Variables
Assigning Values
 Assigning values to variables
 Use the = operator

 The = operator
 Holds a variable identifier on the left

 Value of the corresponding data type on the right


 Or expression of compatible type
 Could be used in a cascade calling
 Where assigning is done from right to left
45
Assigning Values – Examples
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 cascading assignments!


46
Initializing Variables
 Initializing
 Means "to assign an 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 variable 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
Initializing Variables
Literals
What are Literals?
 Literals are:
 Representations of values in the source code
 There are several 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. 0xFE, 0xA8F1, 0xFFFFFFFF


 The 'u' and 'U' suffixes mean a ulong or uint type

 E.g. 12345678U, 0U
 The 'l' and 'L' suffixes mean a long or ulong

 E.g. 9876543L, 0L
53
Integer Literals – Examples
 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:
// The following causes an error because 12.5 is double by default
float realNumber = 12.5;

 A correct way to assign a floating-point value


// The following is the correct way of assigning the value:
float realNumber = 12.5f;

 Exponential format for assigning float values:


// This is the same value in exponential format:
float realNumber = 6.02e+23;
float realNumber = 1.25e-7f;
56
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 (letter 'o')
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>"


 The value is a sequence of character literals

string s = "I am a sting literal";

 May have a @ prefix which ignores the used escaping sequences:


@"<value>"
string s = @"C:\WINDOWS\System32\drivers\beep.sys";
60
String Literals – Examples
 Benefits of quoted strings (with the @ prefix):
// Here is a string literal using escape sequences
string quotation = "\"Hello, Jude\", he said.";
string path = "C:\\Windows\\notepad.exe";

// Here is an example of the usage of @


quotation = @"""Hello, Jimmy!"", she answered.";
path = @"C:\Windows\notepad.exe";

string str = @"some


text";

 In quoted strings "" is used instead of \"! 61


String Literals
Nullable Types

63
Nullable Types
 Nullable types are instances of the System.Nullable
structure
 Wrapper around 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
64
Nullable Types – Example
 Example with int:
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);

 Example with double:


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);
65
Nullable Types
Summary
 Data types are domains of possible values
 E.g. number, character, date, string

 Integer types hold whole numbers


 E.g. 5, -2, 32768

 Float and double hold floating-point numbers


 E.g. 3.14159206, 6.02e+23

 Decimal type holds money and financial information, e.g. 12.80


 Boolean type holds true or false
67
Summary (2)
 Character type holds a single Unicode character
 E.g. 'A', '\n', '0', '€', '\u0AF4'
 String type hold a text, e.g. "Hello C#"
 Object type hold any value
 E.g. string, number, character, date, …
 Variables are named pieces of memory that hold a value
 Identifiers are the names of variables, classes, methods, etc.
 Literals are the values of the primitive types, e.g. 0xFE, '\uF7B3'
 Nullable types can hold a value or null (absence of value)
68
Primitive Data Types and Variables

You might also like