C# - Type Conversion (Type Casting)
Type conversion
in C# means converting one data type into another. It is also known as type
casting. There are mainly two types of type casting in C#: implicit type
conversion and explicit type conversion.
1. Implicit Type Conversion
Implicit type
conversion is automatically handled by the C# compiler. It happens when the
conversion is safe and no data will be lost. This usually includes conversions
from a smaller data type to a larger data type, such as from int to double, or from a derived class to a base class.
For example:
If we have an integer variable a with value 9, and we assign
it to a double variable b, the compiler automatically converts
it.
int a = 9;
double b = a;
Here, a is
automatically converted to a double type. When we print both values using Console.WriteLine, the output will be:
9
9
2. Explicit Type Conversion
Explicit type
conversion, also known as manual casting, is done by the programmer using a
cast operator. This type of conversion is used when converting from a larger
data type to a smaller one, or between incompatible types. It can result in
data loss.
For example:
If we have a double variable a with value 9.78, and we want to convert it into an integer:
double a = 9.78;
int b = (int)a;
In this case,
we are manually converting a to an integer by placing (int) in front of the variable. This will cut off the decimal part and the
output will be:
9.78
9
3. Type Conversion Using Built-in Methods
C# provides a
set of built-in methods in the Convert class for converting between data
types. These methods allow safe and easy conversions between types like int,
string, double, boolean, etc.
Some commonly
used methods include:
- Convert.ToString() – converts any value to a string.
- Convert.ToDouble() – converts a value to a double.
- Convert.ToInt32() – converts a value to a 32-bit
integer.
- Convert.ToBoolean() – converts a value to a boolean.
Example:
int a = 20;
double e = 2.25;
bool b = true;
Console.WriteLine(Convert.ToString(a)); //
Outputs "20"
Console.WriteLine(Convert.ToDouble(a)); // Outputs 20.0
Console.WriteLine(Convert.ToInt32(e)); // Outputs 2
Console.WriteLine(Convert.ToString(b)); // Outputs "True"
4. Using Int32.Parse() Method
In addition to
the Convert class, we can also use the Parse() method to convert a string to an integer. The string must be a valid
numeric value.
Example:
string input = "123";
int result = Int32.Parse(input);
Console.WriteLine(result);
This will
convert the string "123" into the integer 123.
Complete Program Example: Converting int to String and
Double
Here is a
complete program that demonstrates how to convert an integer into a string and
a double using the Convert class.
using System;
namespace Conversion {
class Program {
static void Main(string[]
args) {
int num = 100;
Console.WriteLine("int value: "
+ num);
// Convert
int to string
string str =
Convert.ToString(num);
Console.WriteLine("string value: " + str);
// Convert
int to double
double
doubleNum = Convert.ToDouble(num);
Console.WriteLine("Double
value: " + doubleNum);
Console.ReadLine();
}
}
}
Output:
int value: 100
string value: 100
Double value: 100
Operators in C#
In C#,
operators are symbols
that perform operations on variables and values, forming the basis of
expressions and enabling various computations and comparisons.
1. Arithmetic
Operators
Arithmetic operators are used to perform mathematical operations such as
addition, subtraction, multiplication, and division.
Operator |
Name |
What It Does |
Example |
+ |
Addition |
Adds two
numbers |
a + b |
- |
Subtraction |
Subtracts one
number from another |
a - b |
* |
Multiplication |
Multiplies
two numbers |
a * b |
/ |
Division |
Divides one
number by another |
a / b |
% |
Modulus |
Gives the
remainder of division |
a % b |
Use: For doing calculations like total
marks, average, or price after discount.
2. Comparison
(Relational) Operators
Comparison operators are used to compare two values and return either true or false.
Operator |
Name |
What It Does |
Example |
== |
Equal to |
Checks if two
values are equal |
a == b |
!= |
Not equal to |
Checks if two
values are not equal |
a != b |
> |
Greater than |
Checks if one
value is more than another |
a > b |
< |
Less than |
Checks if one
value is less than another |
a < b |
>= |
Greater or
equal |
Checks if one
value is more or equal |
a >= b |
<= |
Less or equal |
Checks if one
value is less or equal |
a <= b |
Use: When making decisions like checking
age, marks, or eligibility.
3. Logical Operators
Logical operators are used to combine two or more conditions and return
a true or false result.
Operator |
Name |
What It Does |
Example |
&& |
AND |
Returns true
only if both conditions are true |
a > 5 && b < 10 |
! |
NOT |
Reverses the
result: true becomes false, and vice versa |
!(a > 5) |
Use: Used in if conditions,
like checking if a student passed and attended class.
4. Assignment
Operators
Assignment operators are used to assign values to variables, and also to
update them.
Operator |
Name |
What It Does |
Example |
= |
Assign |
Stores a
value in a variable |
a = 5 |
+= |
Add and
assign |
Adds value to
variable |
a += 5 |
-= |
Subtract and
assign |
Subtracts
value from variable |
a -= 3 |
*= |
Multiply and
assign |
Multiplies
variable by a value |
a *= 2 |
/= |
Divide and
assign |
Divides
variable by a value |
a /= 4 |
%= |
Modulus and
assign |
Stores
remainder in the variable |
a %= 2 |
Use: Helpful for updating scores, totals,
or counts in programs.
5. Unary Operators
Unary operators work with a single variable to change its value or
state.
Operator |
Name |
What It Does |
Example |
+ |
Positive |
Keeps the
number positive |
+a |
- |
Negative |
Changes the
number to negative |
-a |
++ |
Increment |
Adds 1 to the
value |
a++ or ++a |
-- |
Decrement |
Subtracts 1
from the value |
a-- or --a |
! |
Logical NOT |
Reverses a
boolean value |
!true is false |
Use: Often used for counters, like
increasing marks or flipping boolean values.
6. Bitwise
Operators (Advanced)
Bitwise operators are used to work with bits (0s and 1s) of integer
values.
Operator |
Name |
What It Does |
Example |
& |
Bitwise AND |
Compares bits
and returns 1 if both are 1 |
a & b |
` |
` |
Bitwise OR |
Compares bits
and returns 1 if any is 1 |
^ |
Bitwise XOR |
Returns 1 if
only one is 1 |
a ^ b |
~ |
Bitwise NOT |
Flips the
bits (0 becomes 1, 1 becomes 0) |
~a |
<< |
Left shift |
Shifts bits
to the left |
a << 2 |
>> |
Right shift |
Shifts bits
to the right |
a >> 2 |
Use: Used in lower-level programming, like
controlling hardware or optimizing memory.
7. Conditional
Operator (Ternary)
A shortcut for if-else that chooses one value based on a condition.
Operator |
Name |
What It Does |
Example |
?: |
Ternary |
Returns one
of two values based on a condition |
max = (a > b) ? a : b; |
Use: For quick decisions like checking
which number is greater.
C# Input for Different Data Types
The simplest way to get input from the user is
by using the ReadLine()
method of the Console
class. However, the Read()
and ReadKey()
methods are also available for getting user input. All three methods are part
of the Console
class.
In C#, all user input from the console is initially taken as a string using Console.ReadLine()
.
To use it as another data type, you must convert
it using methods like Convert.ToInt32()
, Convert.ToDouble()
, etc.
1. String Input
Console.Write(
"Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine(
"Hello " + name);
2. Integer
(int
)
Input
Console.Write(
"Enter your age: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(
"Age: " + age);
Alternative:
int age =
int.Parse(Console.ReadLine());
3. Float Input
Console.Write(
"Enter your height in meters: ");
float height =
float.Parse(Console.ReadLine());
Console.WriteLine(
"Height: " + height);
Note: float.Parse()
may need f
at
the end when assigning values directly (e.g., 1.75f
), but not from
input.
4. Double
Input
Console.Write(
"Enter your GPA: ");
double gpa = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(
"GPA: " + gpa);
5. Boolean (bool
)
Input
Console.Write(
"Are you a student? (true/false): ");
bool isStudent = Convert.ToBoolean(Console.ReadLine());
Console.WriteLine(
"Student: " + isStudent);
Character (char
)
Input
Console.Write(
"Enter a character: ");
char ch = Convert.ToChar(Console.ReadLine());
Console.WriteLine(
"Character: " + ch);
Alternatively, using ReadKey()
:
Console.Write(
"Press a key: ");
char ch = Console.ReadKey().KeyChar;
Difference between ReadLine(), Read() and ReadKey() method:
Method |
What it does |
Return Type |
Example Use |
Read() |
Reads a single
character as ASCII (int) |
int |
int ch = Console.Read(); |
ReadLine() |
Reads the entire
line of text |
string |
string name = Console.ReadLine(); |
ReadKey() |
Reads a single
key press |
ConsoleKeyInfo |
ConsoleKeyInfo key =
Console.ReadKey(); |
Comments
Post a Comment