SlideShare a Scribd company logo
1 of 17
C#
LECTURE
Abid Kohistani
Data Types
As explained in the variables chapter, a variable in C# must be a specified by data type In C#, there
are different types of variables (defined with different keywords), for example:
int myNum = 5; // Integer (whole number)
double myDoubleNum = 5.99D; // Floating point number
char myLetter = 'D'; // Character
bool myBool = true; // Boolean
string myText = "Hello"; // String
Why to use Data Types….
A data type specifies the size and type of variable values.
It is important to use the correct data type for the corresponding variable;
 to avoid errors,
to save time and memory
it will also make your code more maintainable and readable.
Common types of Data Types
Data Type Size Description
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
bool 1 bit Stores true or false values
char 2 bytes Stores a single character/letter, surrounded by single quotes
string 2 bytes per
character
Stores a sequence of characters, surrounded by double quotes
Numbers
Number types are divided into two groups:
Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are int
and long. Which type you should use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or more decimals. Valid types are
float and double.
Integer Types
Int: The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial,
the int data type is the preferred data type when we create variables with a numeric value.
Example :
int myNum = 100000;
Console.WriteLine(myNum);
◦ Long: The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807.
This is used when int is not large enough to store the value. Note that you should end the value with an "L":
Example :
long myNum = 15000000000L;
Console.WriteLine(myNum);
Floating point types
Float: The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the
value with an "F":
Example :
float myNum = 5.75F;
Console.WriteLine(myNum);
◦ Double: The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you can end
the value with a "D" (although not required):
Example :
double myNum = 19.99D;
Console.WriteLine(myNum);
The precision of a floating point value indicates how many digits the value can have after the decimal point. The
precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits.
Therefore it is safer to use double for most calculations.
Scientific Number
A floating point number can also be a scientific number with an "e" to
indicate the power of 10:
Example:
bool isCSharpFun = true;
bool isFishTasty = false;
Console.WriteLine(isCSharpFun); // Outputs True
Console.WriteLine(isFishTasty); // Outputs False
float f1 = 35e3F;
double d1 = 12E4D;
Console.WriteLine(f1);
Console.WriteLine(d1);
Boolean:A boolean data type is declared with
the bool keyword and can only take the values true
or false:
Boolean values are mostly used for conditional testing, which you will learn more about in a later chapter.
Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c': char myGrade = 'B';
Console.WriteLine(myGrade);
Strings: The string data type is used to store a sequence of characters (text).
String values must be surrounded by double quotes:
Example :
string greeting = "Hello World";
Console.WriteLine(greeting);
C# Type Casting
Type casting is when you assign a value of one data type to another type.
In C#, there are two types of casting:
 Implicit Casting (automatically) - converting a smaller type to a larger type size
char -> int -> long -> float -> double
 Explicit Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char
Implicit Casting
Implicit casting is done automatically when passing a smaller size type
to a larger size type:
Example:
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9
Explicit Casting
Explicit casting must be done manually by placing the type in
parentheses in front of the value:
Example:
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
Console.WriteLine(myDouble); // Outputs 9.78
Console.WriteLine(myInt); // Outputs 9
Type Conversion Methods
It is also possible to convert data types explicitly by using built-in methods, such as
Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and
Convert.ToInt64 (long):
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int
Console.WriteLine(Convert.ToString(myBool)); // convert bool to
Why Conversion?
Many times, there's no need for type conversion. But sometimes you have to. Take a
look at the next chapter, when working with user input, to see an example of this
User Input
Get User Input
You have already learned that Console.WriteLine() is used to output (print) values. Now we will use
Console.ReadLine() to get user input.
In the following example, the user can input his or hers username, which is stored in the variable
userName. Then we print the value of userName:
// Type your username and press enter
Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and store it in the variable
string userName = Console.ReadLine();
// Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);
User Input and Numbers
The Console.ReadLine() method returns a string. Therefore, you cannot get information from
another data type, such as int. The following program will cause an error:
 The error message will be something like this:
 Cannot implicitly convert type 'string' to 'int’
 Like the error message says, you cannot implicitly convert type 'string' to
'int'.
 Luckily, for you, you just learned from the previous chapter (Type
Casting), that you can convert any type explicitly, by using one of the
Convert.To methods:
Console.WriteLine("Enter your age:");
int age = Console.ReadLine();
Console.WriteLine("Your age is: " + age);
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
Note: If you enter wrong input (e.g.
text in a numerical input), you will
get an exception/error message (like
System.FormatException:'Input
string was not in a correct format.').
END

More Related Content

What's hot (20)

Computer Science:Pointers in C
Computer Science:Pointers in CComputer Science:Pointers in C
Computer Science:Pointers in C
 
String in c programming
String in c programmingString in c programming
String in c programming
 
String functions in C
String functions in CString functions in C
String functions in C
 
C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#C# lecture 2: Literals , Variables and Data Types in C#
C# lecture 2: Literals , Variables and Data Types in C#
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
 
concept of Array, 1D & 2D array
concept of Array, 1D & 2D arrayconcept of Array, 1D & 2D array
concept of Array, 1D & 2D array
 
Data types
Data typesData types
Data types
 
C++ string
C++ stringC++ string
C++ string
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Constants in java
Constants in javaConstants in java
Constants in java
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
C functions
C functionsC functions
C functions
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Printf and scanf
Printf and scanfPrintf and scanf
Printf and scanf
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 

Similar to C# Data Types and User Input Lecture

C++ Tutorial.docx
C++ Tutorial.docxC++ Tutorial.docx
C++ Tutorial.docxPinkiVats1
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and VariablesIntro C# Book
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answerVasuki Ramasamy
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingSherwin Banaag Sapin
 
2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdf2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdfTrnThBnhDng
 
02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variablesmaznabili
 
C programming tutorial
C programming tutorialC programming tutorial
C programming tutorialMohit Saini
 
Programming in C - interview questions.pdf
Programming in C - interview questions.pdfProgramming in C - interview questions.pdf
Programming in C - interview questions.pdfSergiuMatei7
 
LESSON1-C_programming (1).GRADE 8 LESSONpptx
LESSON1-C_programming (1).GRADE 8 LESSONpptxLESSON1-C_programming (1).GRADE 8 LESSONpptx
LESSON1-C_programming (1).GRADE 8 LESSONpptxjoachimbenedicttulau
 
C programming notes.pdf
C programming notes.pdfC programming notes.pdf
C programming notes.pdfAdiseshaK
 

Similar to C# Data Types and User Input Lecture (20)

C++ Tutorial.docx
C++ Tutorial.docxC++ Tutorial.docx
C++ Tutorial.docx
 
JAVA LESSON-01.pptx
JAVA LESSON-01.pptxJAVA LESSON-01.pptx
JAVA LESSON-01.pptx
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
 
2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdf2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdf
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
02 Primitive data types and variables
02 Primitive data types and variables02 Primitive data types and variables
02 Primitive data types and variables
 
C programming tutorial
C programming tutorialC programming tutorial
C programming tutorial
 
Programming in C.pptx
Programming in C.pptxProgramming in C.pptx
Programming in C.pptx
 
Programming in C - interview questions.pdf
Programming in C - interview questions.pdfProgramming in C - interview questions.pdf
Programming in C - interview questions.pdf
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Datatypes in c
Datatypes in cDatatypes in c
Datatypes in c
 
LESSON1-C_programming (1).GRADE 8 LESSONpptx
LESSON1-C_programming (1).GRADE 8 LESSONpptxLESSON1-C_programming (1).GRADE 8 LESSONpptx
LESSON1-C_programming (1).GRADE 8 LESSONpptx
 
C programming notes.pdf
C programming notes.pdfC programming notes.pdf
C programming notes.pdf
 
C programming notes
C programming notesC programming notes
C programming notes
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Java Basics 1.pptx
Java Basics 1.pptxJava Basics 1.pptx
Java Basics 1.pptx
 

More from Abid Kohistani

Algorithm in Computer, Sorting and Notations
Algorithm in Computer, Sorting  and NotationsAlgorithm in Computer, Sorting  and Notations
Algorithm in Computer, Sorting and NotationsAbid Kohistani
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Abid Kohistani
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
Access Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAccess Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAbid Kohistani
 
OOP in C# Classes and Objects.
OOP in C# Classes and Objects.OOP in C# Classes and Objects.
OOP in C# Classes and Objects.Abid Kohistani
 
Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Abid Kohistani
 
Conditions In C# C-Sharp
Conditions In C# C-SharpConditions In C# C-Sharp
Conditions In C# C-SharpAbid Kohistani
 
C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)Abid Kohistani
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Abid Kohistani
 

More from Abid Kohistani (9)

Algorithm in Computer, Sorting and Notations
Algorithm in Computer, Sorting  and NotationsAlgorithm in Computer, Sorting  and Notations
Algorithm in Computer, Sorting and Notations
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Access Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAccess Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and Encapsulation
 
OOP in C# Classes and Objects.
OOP in C# Classes and Objects.OOP in C# Classes and Objects.
OOP in C# Classes and Objects.
 
Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.
 
Conditions In C# C-Sharp
Conditions In C# C-SharpConditions In C# C-Sharp
Conditions In C# C-Sharp
 
C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)
 

Recently uploaded

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 

C# Data Types and User Input Lecture

  • 2. Data Types As explained in the variables chapter, a variable in C# must be a specified by data type In C#, there are different types of variables (defined with different keywords), for example: int myNum = 5; // Integer (whole number) double myDoubleNum = 5.99D; // Floating point number char myLetter = 'D'; // Character bool myBool = true; // Boolean string myText = "Hello"; // String
  • 3. Why to use Data Types…. A data type specifies the size and type of variable values. It is important to use the correct data type for the corresponding variable;  to avoid errors, to save time and memory it will also make your code more maintainable and readable.
  • 4. Common types of Data Types Data Type Size Description int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647 long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits bool 1 bit Stores true or false values char 2 bytes Stores a single character/letter, surrounded by single quotes string 2 bytes per character Stores a sequence of characters, surrounded by double quotes
  • 5. Numbers Number types are divided into two groups: Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are int and long. Which type you should use, depends on the numeric value. Floating point types represents numbers with a fractional part, containing one or more decimals. Valid types are float and double.
  • 6. Integer Types Int: The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial, the int data type is the preferred data type when we create variables with a numeric value. Example : int myNum = 100000; Console.WriteLine(myNum); ◦ Long: The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that you should end the value with an "L": Example : long myNum = 15000000000L; Console.WriteLine(myNum);
  • 7. Floating point types Float: The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value with an "F": Example : float myNum = 5.75F; Console.WriteLine(myNum); ◦ Double: The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you can end the value with a "D" (although not required): Example : double myNum = 19.99D; Console.WriteLine(myNum); The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations.
  • 8. Scientific Number A floating point number can also be a scientific number with an "e" to indicate the power of 10: Example: bool isCSharpFun = true; bool isFishTasty = false; Console.WriteLine(isCSharpFun); // Outputs True Console.WriteLine(isFishTasty); // Outputs False float f1 = 35e3F; double d1 = 12E4D; Console.WriteLine(f1); Console.WriteLine(d1); Boolean:A boolean data type is declared with the bool keyword and can only take the values true or false: Boolean values are mostly used for conditional testing, which you will learn more about in a later chapter.
  • 9. Characters The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c': char myGrade = 'B'; Console.WriteLine(myGrade); Strings: The string data type is used to store a sequence of characters (text). String values must be surrounded by double quotes: Example : string greeting = "Hello World"; Console.WriteLine(greeting);
  • 10. C# Type Casting Type casting is when you assign a value of one data type to another type. In C#, there are two types of casting:  Implicit Casting (automatically) - converting a smaller type to a larger type size char -> int -> long -> float -> double  Explicit Casting (manually) - converting a larger type to a smaller size type double -> float -> long -> int -> char
  • 11. Implicit Casting Implicit casting is done automatically when passing a smaller size type to a larger size type: Example: int myInt = 9; double myDouble = myInt; // Automatic casting: int to double Console.WriteLine(myInt); // Outputs 9 Console.WriteLine(myDouble); // Outputs 9
  • 12. Explicit Casting Explicit casting must be done manually by placing the type in parentheses in front of the value: Example: double myDouble = 9.78; int myInt = (int) myDouble; // Manual casting: double to int Console.WriteLine(myDouble); // Outputs 9.78 Console.WriteLine(myInt); // Outputs 9
  • 13. Type Conversion Methods It is also possible to convert data types explicitly by using built-in methods, such as Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and Convert.ToInt64 (long): int myInt = 10; double myDouble = 5.25; bool myBool = true; Console.WriteLine(Convert.ToString(myInt)); // convert int to string Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int Console.WriteLine(Convert.ToString(myBool)); // convert bool to
  • 14. Why Conversion? Many times, there's no need for type conversion. But sometimes you have to. Take a look at the next chapter, when working with user input, to see an example of this
  • 15. User Input Get User Input You have already learned that Console.WriteLine() is used to output (print) values. Now we will use Console.ReadLine() to get user input. In the following example, the user can input his or hers username, which is stored in the variable userName. Then we print the value of userName: // Type your username and press enter Console.WriteLine("Enter username:"); // Create a string variable and get user input from the keyboard and store it in the variable string userName = Console.ReadLine(); // Print the value of the variable (userName), which will display the input value Console.WriteLine("Username is: " + userName);
  • 16. User Input and Numbers The Console.ReadLine() method returns a string. Therefore, you cannot get information from another data type, such as int. The following program will cause an error:  The error message will be something like this:  Cannot implicitly convert type 'string' to 'int’  Like the error message says, you cannot implicitly convert type 'string' to 'int'.  Luckily, for you, you just learned from the previous chapter (Type Casting), that you can convert any type explicitly, by using one of the Convert.To methods: Console.WriteLine("Enter your age:"); int age = Console.ReadLine(); Console.WriteLine("Your age is: " + age); Console.WriteLine("Enter your age:"); int age = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Your age is: " + age); Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like System.FormatException:'Input string was not in a correct format.').
  • 17. END