Sitemap

Deep Dive into C# Type Conversions: Techniques and Best Practices

5 min readJul 27, 2024

--

Hello! In this post, we will explore how to perform type conversions in C#. Type conversions are essential for transforming data values from one type to another, enabling us to perform appropriate operations on the data. Understanding how and when to use type conversions can prevent errors and improve the efficiency of your code. Let’s dive in!

Type Conversions:

During the software development process, we may need to change the types of the values we work with. Type conversions allow us to perform operations that are suitable for the data’s inherent type. For example, if we have a numerical value stored as a string, such as string number = "123", we can convert it to an int, bool, or char to perform type-appropriate operations on it.

When we receive values from different services and need to convert them to suitable types, type conversion becomes necessary.

Important!

The goal of type conversions is to transform the type of the data to a compatible one. Converting data to an incompatible type is not possible and will result in an error. To avoid errors, we must ensure that the target type is appropriate for the given data. For example:

  • (String) "123" can be converted to int or decimal, but not to bool.
  • (String) "Hilmi" cannot be converted to int, bool, or char because the value is not compatible.
  • (String) "a" can only be converted to char.
  • (int) 123 can be converted to string or char, but not to bool.

When performing type conversions, it is crucial to select a target type that is appropriate for the value’s type to avoid runtime errors.

Now, let’s examine conversions based on types:

Converting Textual Values to Other Types:

To convert a string value to a suitable type, we can use two methods: Parseand Convert.

Parse Function:

The Parse function is used to convert string values to the target type.

Type x = type.Parse(…)

Example:

string y = "123";
short z = short.Parse(y);

string maritalStatus = "true";
bool _maritalStatus = bool.Parse(maritalStatus);

Convert Functions:

The Convert functions are used to convert values to the target type. Unlike the Parse function, Convert is not limited to string types and can be used for any type.

string x = "123";
int _x = Convert.ToInt32(x);

string y = "3.14";
double _y = Convert.ToDouble(y);

Converting Other Values to Textual Values:

To convert a value to a string type, we can use either Convert or ToString.

Example with Convert:

int a = 24;
string _a = Convert.ToString(a);

ToString Function:

The ToString function is available for all types and can easily convert any type to a string.

float f = 25;
string _f = f.ToString();

Converting Between Numerical Types:

Numeric types may require different approaches when converting among themselves. These approaches are implicit type conversion and explicit type conversion.

Implicit Type Conversion

When a numerical value is converted to another type with a larger range, no additional steps are needed. This process is called implicit conversion.

Get eminy’s stories in your inbox

Join Medium for free to get updates from this writer.

Implicit type conversion is the process of converting a numeric value to another numeric type with a larger range.

Press enter or click to view image in full size
Implicit type conversion is the process of converting a numeric value to another numeric type with a larger range.

Example of Implicit Conversion:

int a = 3000;
float f = a; // Here, an implicit conversion occurs. The compiler automatically handles it.

short x = 123;
long y = x;

Explicit Type Conversion

When converting a numerical value to a type with a smaller range, the target type may not be able to accommodate the value. Due to the risk of not fitting into the range of that type, this operation needs to be performed explicitly. This requires explicit conversion to handle the potential data loss.

Press enter or click to view image in full size
Explicit type conversion is the process of assigning a numeric value to a type with a smaller range. Due to the size mismatch, data loss is possible in this case.
Explicit type conversion is the process of assigning a numeric value to a type with a smaller range

Example of Explicit Conversion:

int x = 3000;
short y = (short)x; // Here, explicit conversion using the cast operator occurs.

int x = 60000;
short _x = (short)x; // Data loss occurs due to the smaller range of short type.

So, what happens if we convert a numeric type to its subtype, and the value does not fit into the range of the subtype?

Press enter or click to view image in full size

In such a case, data loss will occur. By data loss, we mean that if the value of an int type is 37000 and it is to be converted to a short type, the short type has a range of 256. In this case, the value 37000 will be repeatedly divided by 256, and the remainder will be the final value, with the rest being considered as data loss.

Handling Explicit Conversions with Checked and Unchecked:

Checked: During explicit conversion, the checked keyword provides a control mechanism that alerts the developer at runtime if data loss is likely.

checked
{
int a = 9123;
byte b = (byte)a; // If data loss is possible, a runtime error is thrown.
}

Unchecked: The unchecked keyword ignores potential data loss and does not throw a runtime error. By default, code blocks are unchecked.

unchecked
{
int a = 9123;
byte b = (byte)a; // Veri kaybı olsa bile runtime'da uyarı vermez.
}

Converting Bool to Numerical Types:

When a boolean value is converted to a numerical type, it follows logical equivalence:

  • true = 1
  • false = 0

Example:

bool b = true;
int i = Convert.ToInt32(b); // i = 1

bool a = false;
double _a = Convert.ToDouble(a); // _a = 0

Converting Numerical Types to Bool:

int i = 1;
bool b = Convert.ToBoolean(i); // b = true

int i = 0;
bool b = Convert.ToBoolean(i); // b = false

int i = 232;
bool b = Convert.ToBoolean(i); // b = true
Press enter or click to view image in full size
ASCII TABLE

Converting Char to Numerical Types:

When converting a character to a numerical type, we use the ASCII code, where each character has a numerical equivalent.

Example:

char a = 'a';
int _a = (int)a; // Uses ASCII code

Converting Numerical Types to Char:

We convert numerical values to their corresponding ASCII character.

int o = 111;
int O = 79;

char _o = (char)o; // _o = 'o'
char _O = (char)O; // _O = 'O'

Conclusion:

✨ I hope this article has helped you understand the various type conversions in C#. From converting strings to numbers and vice versa, to handling boolean and character conversions, mastering these techniques is crucial for effective coding. Stay tuned for more insights and tips on C# and .NET! ✨

Acknowledgments:

This article was inspired by the teachings of Gençay Yıldız. His insights and guidance have greatly influenced the content and direction of this post.⭐️

--

--