Web Technology: Semester-Spring 2020
Web Technology: Semester-Spring 2020
Type Casting
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
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):
Example:
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 string
Why Conversion?
Many times, there's no need for type conversion. But sometimes you have to.
C# 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:
Example
Console.WriteLine("Enter username:");
string userName = Console.ReadLine();
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:
Example
Console.WriteLine("Enter your age:");
int age = Console.ReadLine();
Console.WriteLine("Your age is: " + age
Error: cannot implicitly convert type 'string' to 'int'.
Resolving Error
Example
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
C# Operators
The C# Math class has many methods that allows you to perform mathematical tasks on
numbers.
Math.Max(x,y)
The Math.Max(x,y) method can be used to find the highest value of x and y:
Example
Math.Max(5, 10);
Math.Min(x,y)
The Math.Min(x,y) method can be used to find the lowest value of of x and y:
Example
Math.Min(5, 10);
Math.Sqrt(x)