SlideShare ist ein Scribd-Unternehmen logo
1 von 41
DATA TYPES, VARIABLES AND
CONSTANT
ITEC102: Fundamentals of Programming
Data Types
A DataType is a classification that specifies which type
of value a variable has and what type of mathematical,
relational or logical operations can be applied to it
without causing an error.
For example, a string is a data type that is used to
classify text and an integer is a data type used to
classify whole numbers.
Primitive and Non-Primitive
C# is a strongly typed language which means that
variables must be explicitly defined.
The compiler will throw an error if a value assigned or
being assigned is not the data type specified.
An example of this is a variable assigned a number
cannot hold text later on in the program.
Also, a variable defined as an integer cannot be assigned
a string.
Strongly typed
A strongly-typed programming language is one in which
each type of data (such as integer, character,
hexadecimal, packed decimal, and so forth) is
predefined as part of the programming language and all
constants or variables defined for a given program must
be described with one of the data types.
https://whatis.techtarget.com/definition/strongly-typed
Primitive (Value Type)
C# primitives are also called value types and
predefined in the .NET framework.
Primitive types can be assigned a value directly.
The value assigned is stored on the stack as opposed to
the heap.
Primitive (Value Type)
A Stack is used for static memory allocation and Heap
for dynamic memory allocation, both stored in the
computer's RAM.
Variables allocated on the stack are stored directly to
the memory and access to this memory is very fast, and
its allocation is dealt with when the program is
compiled.
Primitive (Value Type)
While value types are stored generally in
the stack, reference types are stored in the
managed heap.
A value type derives from System.ValueType and
contains the data inside its own memory allocation.
In other words, variables or objects or value types have
their own copy of the data.
Available value types in C# 2010
Type Represents Range DefaultValue
bool Boolean value True or False False
byte 8-bit unsigned integer 0 to 255 0
char 16-bit Unicode character U +0000 to U +ffff ‘0’
decimal
128-bit precise decimal values with 28-29
significant digits
(-7.9 x 1028 to 7.9 x 1028) / 100 to 28 0.0M
double 64-bit double-precision floating point type (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 0.0D
float 32-bit single-precision floating point type -3.4 x 1038 to + 3.4 x 1038 0.0F
Available value types in C# 2010
int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0
long 64-bit signed integer type
-923,372,036,854,775,808 to
9,223,372,036,854,775,807
0L
sbyte 8-bit signed integer type -128 to 127 0
short 16-bit signed integer type -32,768 to 32,767 0
uint 32-bit unsigned integer type 0 to 4,294,967,295 0
ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0
ushort 16-bit unsigned integer type 0 to 65,535 0
Non-primitive (Reference Type)
The reference types do not contain the actual data stored in
a variable, but they contain a reference to the variables.
In other words, they refer to a memory location.
Using multiple variables, the reference types can refer to a
memory location.
If the data in the memory location is changed by one of the
variables, the other variable automatically reflects this
change in value.
Object Type
The ObjectType is the ultimate base class for all data
types in C# CommonType System (CTS).
The object types can be assigned values of any other
types, value types, reference types, predefined or user-
defined types.
However, before assigning values, it needs type
conversion.
Boxing / Unboxing
When a value type is converted to object type, it is
called boxing and on the other hand, when an object
type is converted to a value type, it is called unboxing.
Boxing Conversion
Unboxing Conversion
Dynamic Type
You can store any type of value in the dynamic data type
variable.Type checking for these types of variables
takes place at run-time.
Syntax for declaring a dynamic type is:
dynamic <variable_name> = value;
For example,
dynamic d = 20;
String Type
The StringType allows you to assign any string values to
a variable.The string type is an alias for the
System.String class. It is derived from object type.The
value for a string type can be assigned using string
literals in two forms: quoted and @quoted.
For example: String str = "Hello Universe";
@"Hello Universe";
Pointer Type
Pointer type variables store the memory address of
another type. Pointers in C# have the same capabilities
as the pointers in C or C++.
Syntax for declaring a pointer type is:
type* identifier;
For example, char* cptr;
int* iptr;
Variables
Variables are used to store information to
be referenced and used inside a program.
Each variable has a specific type, which
determines the size and layout of the
variable's memory, the range of values that
can be stored within that memory, and the
set of operations that can be applied to the
variable.
Variables
Type Example
Integral types
sbyte, byte, short, ushort, int, uint, long, ulong, and
char
Floating point types float and double
Decimal types decimal
Boolean types true or false values, as assigned
Nullable types Nullable data types
Defining Variables
Syntax for variable definition in C# is:
<data_type> <variable_list>;
Here, data_type must be a valid C# data type including
char, int, float, double, or any user-defined data type,
and variable_list may consist of one or more identifier
names separated by commas.
Some valid variable definitions
int i, j, k;
char c, ch;
float f, salary;
double d;
Variable Names
To use variables in your C# programs, you must know
how to create variable names.
In C#, variable names must adhere to the following
rules:
Variable Names
The name can contain letters, digits, and the underscore
character (_).
The first character of the name must be a letter.The
underscore is also a legal first character, but its use is not
recommended at the beginning of a name.An underscore
is often used with special commands, and it's sometimes
hard to read.
Variable Names
Case matters (that is, upper- and lowercase letters). C# is
case-sensitive; thus, the names count and Count refer to
two different variables.
C# keywords can't be used as variable names. Recall that a
keyword is a word that is part of the C# language.
valid and invalid C# variable names:
Variable
Name
Legality
Percent Legal
y2x5__w7h3 Legal
yearly_cost Legal
_2010_tax Legal, but not advised
valid and invalid C# variable names:
Variable Name Legality
Percent Legal
y2x5__w7h3 Legal
yearly_cost Legal
_2010_tax Legal, but not advised
checking#account Illegal; contains the illegal character #
double Illegal; is a C keyword
9byte Illegal; first character is a digit
Initializing Variables
Variables are initialized (assigned a value) with an equal
sign followed by a constant expression.The general
form of initialization is:
variable_name = value;
You can initialize a variable at the time of definition as:
int i = 100;
Initializing Variables
Variables can be initialized in their declaration.The
initializer consists of an equal sign followed by a
constant expression as:
<data_type> <variable_name> = value;
Initializing Variables
Some examples are:
int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */
using System;
namespaceVariableDefinition
{
class Program
{
static void Main(string[] args)
{
short a;
int b;
double c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
This example
uses various
types of
variables
When the above code is
compiled and executed, it
produces the following result:
a = 10, b = 20, c = 30
Accepting Value from User
The simplest method to get input from the user is by
using the ReadLine() method of the Console class.
However, Read() and ReadKey() are also available for
getting input from the user.They are also included
in Console class.
string testString;
Console.Write("Enter a string - ");
testString = Console.ReadLine();
Console.WriteLine("You entered '{0}'", testString);
Difference between ReadLine(), Read()
and ReadKey() method:
ReadLine(): reads the next line of input from the
standard input stream. It returns the same string.
Read(): reads the next character from the standard
input stream. It returns the ascii value of the character.
ReadKey(): obtains the next key pressed by user.This
method is usually used to hold the screen until user
press a key.
Lvalue and Rvalue in C#
There are two kinds of expressions in C#:
1. lvalue: An expression that is an lvalue may appear as
either the left-hand or right-hand side of an
assignment.
2. rvalue: An expression that is an rvalue may appear on
the right- but not left-hand side of an assignment.
Lvalue and Rvalue in C#
Following is a valid C# statement:
int g = 20;
But following is not a valid statement and would
generate compile-time error:
10 = 20;
Constants
Constants are immutable values which are known at
compile time and do not change for the life of the
program.
Constants are declared with the const modifier.
Only the C# built-in types (excluding System.Object)
may be declared as “const”
Integer Literal
An integer literal can be a decimal, octal, or hexadecimal
constant. A prefix specifies the base or radix: 0x or 0X for
hexadecimal, 0 for octal, and no prefix id for decimal.
An integer literal can also have a suffix that is a
combination of U and L, for unsigned and long,
respectively.The suffix can be uppercase or
lowercase and can be in any order.
Integer Literal
Here are some examples of integer literals:
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Integer Literal
Following are other examples of various types of Integer
literals:
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-Point Literal
A floating-point literal has an integer part, a decimal point, a
fractional part, and an exponent part.You can represent
floating point literals either in decimal form or exponential
form.
Here are some examples of floating-point literals:
 3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
escape sequence codes
Escape sequence Meaning
  character
' ' character
" " character
? ? character
a Alert or bell
b Backspace
f Form feed
n Newline
r Carriage return
t Horizontal tab
v Vertical tab
ooo Octal number of one to three digits
xhh . . . Hexadecimal number of one or more digits

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
C# Loops
C# LoopsC# Loops
C# Loops
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
C# in depth
C# in depthC# in depth
C# in depth
 
C# Lab Programs.pdf
C# Lab Programs.pdfC# Lab Programs.pdf
C# Lab Programs.pdf
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java servlets
Java servletsJava servlets
Java servlets
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
c# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming Conventionsc# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming Conventions
 
Comments in C Programming
Comments in C ProgrammingComments in C Programming
Comments in C Programming
 
Operators and expression in c#
Operators and expression in c#Operators and expression in c#
Operators and expression in c#
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Event Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdfEvent Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdf
 
Control statements
Control statementsControl statements
Control statements
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 

Ähnlich wie Data Types, Variables, and Constants in C# Programming

Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answerVasuki Ramasamy
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# programMAHESHV559910
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfssusera0bb35
 
Learn C# Programming - Variables & Constants
Learn C# Programming - Variables & ConstantsLearn C# Programming - Variables & Constants
Learn C# Programming - Variables & ConstantsEng Teong Cheah
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming conceptsandeshjadhav28
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++Rokonuzzaman Rony
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic conceptsAbhinav Vatsa
 
C programming tutorial
C programming tutorialC programming tutorial
C programming tutorialMohit Saini
 
5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt5-Lec - Datatypes.ppt
5-Lec - Datatypes.pptAqeelAbbas94
 
C programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer CentreC programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer Centrejatin batra
 
Introduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh SinghIntroduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh Singhsinghadarsh
 

Ähnlich wie Data Types, Variables, and Constants in C# Programming (20)

Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
 
PSPC--UNIT-2.pdf
PSPC--UNIT-2.pdfPSPC--UNIT-2.pdf
PSPC--UNIT-2.pdf
 
Data type
Data typeData type
Data type
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Learn C# Programming - Variables & Constants
Learn C# Programming - Variables & ConstantsLearn C# Programming - Variables & Constants
Learn C# Programming - Variables & Constants
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
 
Data Handling
Data HandlingData Handling
Data Handling
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic concepts
 
LEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMTLEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMT
 
C programming tutorial
C programming tutorialC programming tutorial
C programming tutorial
 
C
CC
C
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
C#
C#C#
C#
 
5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt
 
C programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer CentreC programming Training in Ambala ! Batra Computer Centre
C programming Training in Ambala ! Batra Computer Centre
 
Introduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh SinghIntroduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh Singh
 

Kürzlich hochgeladen

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Kürzlich hochgeladen (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Data Types, Variables, and Constants in C# Programming

  • 1. DATA TYPES, VARIABLES AND CONSTANT ITEC102: Fundamentals of Programming
  • 2. Data Types A DataType is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error. For example, a string is a data type that is used to classify text and an integer is a data type used to classify whole numbers.
  • 3. Primitive and Non-Primitive C# is a strongly typed language which means that variables must be explicitly defined. The compiler will throw an error if a value assigned or being assigned is not the data type specified. An example of this is a variable assigned a number cannot hold text later on in the program. Also, a variable defined as an integer cannot be assigned a string.
  • 4. Strongly typed A strongly-typed programming language is one in which each type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types. https://whatis.techtarget.com/definition/strongly-typed
  • 5.
  • 6. Primitive (Value Type) C# primitives are also called value types and predefined in the .NET framework. Primitive types can be assigned a value directly. The value assigned is stored on the stack as opposed to the heap.
  • 7. Primitive (Value Type) A Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM. Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and its allocation is dealt with when the program is compiled.
  • 8.
  • 9. Primitive (Value Type) While value types are stored generally in the stack, reference types are stored in the managed heap. A value type derives from System.ValueType and contains the data inside its own memory allocation. In other words, variables or objects or value types have their own copy of the data.
  • 10. Available value types in C# 2010 Type Represents Range DefaultValue bool Boolean value True or False False byte 8-bit unsigned integer 0 to 255 0 char 16-bit Unicode character U +0000 to U +ffff ‘0’ decimal 128-bit precise decimal values with 28-29 significant digits (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 0.0M double 64-bit double-precision floating point type (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 0.0D float 32-bit single-precision floating point type -3.4 x 1038 to + 3.4 x 1038 0.0F
  • 11. Available value types in C# 2010 int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0 long 64-bit signed integer type -923,372,036,854,775,808 to 9,223,372,036,854,775,807 0L sbyte 8-bit signed integer type -128 to 127 0 short 16-bit signed integer type -32,768 to 32,767 0 uint 32-bit unsigned integer type 0 to 4,294,967,295 0 ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0 ushort 16-bit unsigned integer type 0 to 65,535 0
  • 12. Non-primitive (Reference Type) The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables. In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value.
  • 13. Object Type The ObjectType is the ultimate base class for all data types in C# CommonType System (CTS). The object types can be assigned values of any other types, value types, reference types, predefined or user- defined types. However, before assigning values, it needs type conversion.
  • 14. Boxing / Unboxing When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing.
  • 17. Dynamic Type You can store any type of value in the dynamic data type variable.Type checking for these types of variables takes place at run-time. Syntax for declaring a dynamic type is: dynamic <variable_name> = value; For example, dynamic d = 20;
  • 18. String Type The StringType allows you to assign any string values to a variable.The string type is an alias for the System.String class. It is derived from object type.The value for a string type can be assigned using string literals in two forms: quoted and @quoted. For example: String str = "Hello Universe"; @"Hello Universe";
  • 19. Pointer Type Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as the pointers in C or C++. Syntax for declaring a pointer type is: type* identifier; For example, char* cptr; int* iptr;
  • 20. Variables Variables are used to store information to be referenced and used inside a program. Each variable has a specific type, which determines the size and layout of the variable's memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable.
  • 21. Variables Type Example Integral types sbyte, byte, short, ushort, int, uint, long, ulong, and char Floating point types float and double Decimal types decimal Boolean types true or false values, as assigned Nullable types Nullable data types
  • 22. Defining Variables Syntax for variable definition in C# is: <data_type> <variable_list>; Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas. Some valid variable definitions int i, j, k; char c, ch; float f, salary; double d;
  • 23. Variable Names To use variables in your C# programs, you must know how to create variable names. In C#, variable names must adhere to the following rules:
  • 24. Variable Names The name can contain letters, digits, and the underscore character (_). The first character of the name must be a letter.The underscore is also a legal first character, but its use is not recommended at the beginning of a name.An underscore is often used with special commands, and it's sometimes hard to read.
  • 25. Variable Names Case matters (that is, upper- and lowercase letters). C# is case-sensitive; thus, the names count and Count refer to two different variables. C# keywords can't be used as variable names. Recall that a keyword is a word that is part of the C# language.
  • 26. valid and invalid C# variable names: Variable Name Legality Percent Legal y2x5__w7h3 Legal yearly_cost Legal _2010_tax Legal, but not advised
  • 27. valid and invalid C# variable names: Variable Name Legality Percent Legal y2x5__w7h3 Legal yearly_cost Legal _2010_tax Legal, but not advised checking#account Illegal; contains the illegal character # double Illegal; is a C keyword 9byte Illegal; first character is a digit
  • 28. Initializing Variables Variables are initialized (assigned a value) with an equal sign followed by a constant expression.The general form of initialization is: variable_name = value; You can initialize a variable at the time of definition as: int i = 100;
  • 29. Initializing Variables Variables can be initialized in their declaration.The initializer consists of an equal sign followed by a constant expression as: <data_type> <variable_name> = value;
  • 30. Initializing Variables Some examples are: int d = 3, f = 5; /* initializing d and f. */ byte z = 22; /* initializes z. */ double pi = 3.14159; /* declares an approximation of pi. */ char x = 'x'; /* the variable x has the value 'x'. */
  • 31. using System; namespaceVariableDefinition { class Program { static void Main(string[] args) { short a; int b; double c; /* actual initialization */ a = 10; b = 20; c = a + b; Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c); Console.ReadLine(); } } } This example uses various types of variables When the above code is compiled and executed, it produces the following result: a = 10, b = 20, c = 30
  • 32. Accepting Value from User The simplest method to get input from the user is by using the ReadLine() method of the Console class. However, Read() and ReadKey() are also available for getting input from the user.They are also included in Console class. string testString; Console.Write("Enter a string - "); testString = Console.ReadLine(); Console.WriteLine("You entered '{0}'", testString);
  • 33. Difference between ReadLine(), Read() and ReadKey() method: ReadLine(): reads the next line of input from the standard input stream. It returns the same string. Read(): reads the next character from the standard input stream. It returns the ascii value of the character. ReadKey(): obtains the next key pressed by user.This method is usually used to hold the screen until user press a key.
  • 34. Lvalue and Rvalue in C# There are two kinds of expressions in C#: 1. lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment. 2. rvalue: An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
  • 35. Lvalue and Rvalue in C# Following is a valid C# statement: int g = 20; But following is not a valid statement and would generate compile-time error: 10 = 20;
  • 36. Constants Constants are immutable values which are known at compile time and do not change for the life of the program. Constants are declared with the const modifier. Only the C# built-in types (excluding System.Object) may be declared as “const”
  • 37. Integer Literal An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and no prefix id for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively.The suffix can be uppercase or lowercase and can be in any order.
  • 38. Integer Literal Here are some examples of integer literals: 212 /* Legal */ 215u /* Legal */ 0xFeeL /* Legal */ 078 /* Illegal: 8 is not an octal digit */ 032UU /* Illegal: cannot repeat a suffix */
  • 39. Integer Literal Following are other examples of various types of Integer literals: 85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */
  • 40. Floating-Point Literal A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part.You can represent floating point literals either in decimal form or exponential form. Here are some examples of floating-point literals:  3.14159 /* Legal */ 314159E-5L /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */
  • 41. escape sequence codes Escape sequence Meaning character ' ' character " " character ? ? character a Alert or bell b Backspace f Form feed n Newline r Carriage return t Horizontal tab v Vertical tab ooo Octal number of one to three digits xhh . . . Hexadecimal number of one or more digits

Hinweis der Redaktion

  1. Certain operations may be allowable only with certain data types. The language compiler enforces the data typing and use compliance. An advantage of strong data typing is that it imposes a rigorous set of rules on a programmer and thus guarantees a certain consistency of results. A disadvantage is that it prevents the programmer from inventing a data type not anticipated by the developers of the programming language and it limits how "creative" one can be in using a given data type.
  2. It is also possible to perform the boxing explicitly as in the following example, but explicit boxing is never required: int i = 123; object o = (object)i;  // explicit boxing
  3. Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time.
  4. The user-defined reference types are: class, interface, or delegate.
  5. Each variable has a specific type, which determines the size and layout of the variable's memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable.
  6. It is a good programming practice to initialize variables properly, otherwise sometimes program may produce unexpected result.
  7. Variables are lvalues and hence they may appear on the left-hand side of an assignment. Numeric literals are rvalues and hence they may not be assigned and cannot appear on the left-hand side.
  8. While representing in decimal form, you must include the decimal point, the exponent, or both; and while representing using exponential form you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.