DEV Community

AllCoderThings
AllCoderThings

Posted on

C# Type Conversions

Originally published at https://allcoderthings.com/en/article/csharp-type-conversions

During programming, we work with different types of data. Data from the user is usually of type string, but in order to perform mathematical operations, this data must be converted into numeric types. At this point, type conversions come into play. In this article, we will examine type conversion methods in C#.

Implicit and Explicit Casting

Conversion from a smaller data type to a larger one is done automatically with implicit casting. However, when converting from a larger type to a smaller one, there is a risk of data loss, so explicit casting must be used.

// Implicit casting
int number = 100;
long big = number;         // automatic conversion
double fraction = number;  // int → double

// Explicit casting
double d = 12.9;
int i = (int)d; // 12, fractional part is lost

byte b = (byte)300; // 300 is too large for byte → overflow occurs
Console.WriteLine(b); // 44
Enter fullscreen mode Exit fullscreen mode

Conversions with the Convert Class

The Convert class allows safe conversions between commonly used types.

string s1 = "42";
int number = Convert.ToInt32(s1);

string s2 = "3.14";
double pi = Convert.ToDouble(s2);

bool status = Convert.ToBoolean(1); // true
string text = Convert.ToString(12345);

Console.WriteLine(number);
Console.WriteLine(pi);
Console.WriteLine(status);
Console.WriteLine(text);
Enter fullscreen mode Exit fullscreen mode

Parse and TryParse Methods

Parse throws an exception on invalid input, while TryParse returns false if the conversion fails.

Parse Examples

int i = int.Parse("123");
double d = double.Parse("12.5");
decimal price = decimal.Parse("99.99");
bool b = bool.Parse("true");

Console.WriteLine(i);
Console.WriteLine(d);
Console.WriteLine(price);
Console.WriteLine(b);
Enter fullscreen mode Exit fullscreen mode

TryParse Examples

Console.Write("Enter a number: ");
string input = Console.ReadLine();

if (int.TryParse(input, out int result))
{
    Console.WriteLine("You entered: " + result);
}
else
{
    Console.WriteLine("Invalid number entered.");
}
Enter fullscreen mode Exit fullscreen mode

Boxing and Unboxing

Wrapping value types inside an object is called boxing, and extracting them back is called unboxing.

int x = 10;

// Boxing
object obj = x;

// Unboxing
int y = (int)obj;
Console.WriteLine(y);

// Wrong unboxing will throw an error
object obj2 = "text";
// int z = (int)obj2; // InvalidCastException
Enter fullscreen mode Exit fullscreen mode

Type Checking and Conversion Operators

is, as operators and GetType, typeof constructs can be used for type checking.

object data = "Hello";

// is operator
if (data is string)
    Console.WriteLine("Data is of type string.");

// as operator
string str = data as string;
if (str != null)
    Console.WriteLine(str.ToUpper());

// GetType and typeof
Console.WriteLine(data.GetType());   // System.String
Console.WriteLine(typeof(int));      // System.Int32
Enter fullscreen mode Exit fullscreen mode

Sample Application

Let’s get product information from the user as strings and convert them into appropriate types.

Console.Write("Product name: ");
string product = Console.ReadLine();

Console.Write("Quantity: ");
string quantityStr = Console.ReadLine();

Console.Write("Unit price: ");
string priceStr = Console.ReadLine();

Console.Write("Discount (%): ");
string discountStr = Console.ReadLine();

Console.Write("In stock? (Y/N): ");
string stockStr = Console.ReadLine();

if (int.TryParse(quantityStr, out int quantity) &&
    decimal.TryParse(priceStr, out decimal unitPrice) &&
    double.TryParse(discountStr, out double discount))
{
    bool inStock = stockStr.Trim().ToUpper() == "Y";

    decimal total = quantity * unitPrice;
    decimal discountAmount = total * (decimal)(discount / 100);
    decimal grandTotal = total - discountAmount;

    Console.WriteLine($"\nProduct: {product}");
    Console.WriteLine($"Quantity: {quantity}");
    Console.WriteLine($"Unit Price: {unitPrice:0.00} EUR");
    Console.WriteLine($"Discount: %{discount}");
    Console.WriteLine($"Stock: {(inStock ? "Available" : "Not Available")}");
    Console.WriteLine($"Total: {grandTotal:0.00} EUR");
}
else
{
    Console.WriteLine("Invalid input.");
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)