Type conversion happens when we assign the value of one data type to another. If the data types are compatible, then C# does Automatic Type Conversion. If not comparable, then they need to be converted explicitly which is known as Explicit Type conversion.
Type Casting can be divided into two parts as mentioned below:
- Implicit Type Conversion (Type Safe)
- Explicit Type Conversion (Manual Conversion)
1. Implicit Type Casting
In C# Implicit Type Casting also known as Automatic type conversion refers to the built-in mechanisms that control the flow of execution in your program without explicitly using timers or scheduling objects. These mechanisms are inherent to the language and the underlying runtime environment.
Conditions of Implicit Type Casting
- The two data types are compatible.
- When we assign the value of a smaller data type to a bigger data type.
The implicit type casting is done automatically when we try to convert small data into large data types.
In C#, the numeric data types are compatible with each other but no automatic conversion is supported from numeric type to char or boolean. Also, char and boolean are not compatible with each other. Before converting, the compiler first checks the compatibility accordingly
Example 1:
C#
// Demonstrating Implicit Type Conversion
using System;
namespace Casting {
class Geeks {
// Main Method
public static void Main(String[] args)
{
int i = 57;
// automatic type conversion
long l = i;
// automatic type conversion
float f = l;
Console.WriteLine("Int value :" + i);
Console.WriteLine("Long value :" + l);
Console.WriteLine("Float value :" + f);
}
}
}
OutputInt value 57
Long value 57
Float value 57
Example 2: This program gives a compilation error because we try to convert a large data type into a small type
C#
// Incompatible Data Conversion
using System;
namespace Casting {
class Geeks {
// Main Method
public static void Main(String[] args)
{
double d = 765.12;
// Incompatible Data Type
int i = d;
// Display Result
Console.WriteLine("Value of i is :", +i);
}
}
}
Output:
main.cs(13,17): error CS0266: Cannot implicitly convert type `double' to `int'. An explicit conversion exists (are you missing a cast?)
Compilation failed: 1 error(s), 0 warnings
Note: If we want to assign a value of larger data type to a smaller data type we perform explicit type casting. It may result into the lossy conversion.
Implicit is not the Solution for such kind of problem where we want to convert a large data type into a small type. So, let check on how we can do this.
2. Explicit Type Casting
Explicit type casting is the process of converting a value of one data type to another data type that is not implicitly compatible. This is necessary when there's a potential for data loss or when the compiler cannot implicitly perform the conversion. When we try to assign a double value to the int data type it leads to a compilation error when types are not compatible with each other
Example 1: Using Explicit Conversion to convert double into int.
C#
// Demonstration of Explicit Type Conversion
using System;
namespace Casting {
class Geeks {
// Main Method
public static void Main(String[] args)
{
double d = 765.12;
// Explicit Type Casting
// larger data into smaller data type
int i = (int)d;
// Display Result
Console.WriteLine("Value of i is " + i);
// the value of i becomes 765 and there is a loss of
// 0.12 value.
}
}
}
This solves our some of the problems, but we can also have some available methods that can help us for conversion mentioned below.
Type Conversion Methods
There are some built in methods defined for type conversions mentioned below:
Method | Descryption |
---|
ToBoolean | It will converts a type to Boolean value |
ToChar | It will converts a type to a character value |
ToByte | It will converts a value to Byte Value |
ToDecimal | It will converts a value to Decimal point value |
ToDouble | It will converts a type to double data type |
ToInt16 | It will converts a type to 16-bit integer |
ToInt32 | It will converts a type to 32 bit integer |
ToInt64 | It will converts a type to 64 bit integer |
ToString | It will converts a given type to string |
ToUInt16 | It will converts a type to unsigned 16 bit integer |
ToUInt32 | It will converts a type to unsigned 32 bit integer |
ToUInt64 | It will converts a type to unsigned 64 bit integer |
Example: Typecasting using built-in methods
C#
// Using Built In Type Conversion Methods
using System;
namespace Casting {
class Geeks {
// Main Method
public static void Main(String[] args)
{
int i = 12;
double d = 765.12;
float f = 56.123F;
// Using Built- In Type Conversion
// Methods & Displaying Result
Console.WriteLine(Convert.ToString(f));
Console.WriteLine(Convert.ToInt32(d));
Console.WriteLine(Convert.ToUInt32(f));
Console.WriteLine(Convert.ToDouble(i));
Console.WriteLine("GeeksforGeeks");
}
}
}
Output56.123
765
56
12
GeeksforGeeks
Similar Reads
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are the fundamental building blocks for communicating with a database management system (DBMS). It is used to interact with the database with some operations. It is also used to perform specific tasks, functions, and queries of data. SQL can perform various tasks like creating a table,
7 min read
TCP/IP Model The TCP/IP model is a framework that is used to model the communication in a network. It is mainly a collection of network protocols and organization of these protocols in different layers for modeling the network.It has four layers, Application, Transport, Network/Internet and Network Access.While
7 min read
Basics of Computer Networking A computer network is a collection of interconnected devices that share resources and information. These devices can include computers, servers, printers, and other hardware. Networks allow for the efficient exchange of data, enabling various applications such as email, file sharing, and internet br
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Introduction to Java Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read
Second Largest Element in an Array Given an array of positive integers arr[] of size n, the task is to find second largest distinct element in the array.Note: If the second largest element does not exist, return -1. Examples:Input: arr[] = [12, 35, 1, 10, 34, 1]Output: 34Explanation: The largest element of the array is 35 and the sec
14 min read
Unified Modeling Language (UML) Diagrams Unified Modeling Language (UML) is a general-purpose modeling language. The main aim of UML is to define a standard way to visualize the way a system has been designed. It is quite similar to blueprints used in other fields of engineering. UML is not a programming language, it is rather a visual lan
14 min read
Python Lists In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Python Operators In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
6 min read
f-strings in Python Python offers a powerful feature called f-strings (formatted string literals) to simplify string formatting and interpolation. f-strings is introduced in Python 3.6 it provides a concise and intuitive way to embed expressions and variables directly into strings. The idea behind f-strings is to make
5 min read