Zum Hauptinhalt springen
Echtzeit-Radar & Feeds
Alle RSS Feeds ➔
👥 Community & Social
••
Sichere ProgrammierungHow Hindsight Turned Deployment #1017 Into the Fix for #1057(29.09.2026 um 06:25 Uhr)
••
Sichere ProgrammierungSystems foundations should start below the framework(29.09.2026 um 06:30 Uhr)
••
Sichere ProgrammierungHow a game should say no: designing refusals people can act on(29.09.2026 um 06:30 Uhr)
••
Sichere ProgrammierungTuring Sim: Making the USD Schemas Inspector Readable(29.09.2026 um 06:31 Uhr)
••••
Sichere ProgrammierungHow Hindsight Turned Deployment #1017 Into the Fix for #1057(29.09.2026 um 06:25 Uhr)
••
Sichere ProgrammierungSystems foundations should start below the framework(29.09.2026 um 06:30 Uhr)
••
Sichere ProgrammierungHow a game should say no: designing refusals people can act on(29.09.2026 um 06:30 Uhr)
••
Sichere ProgrammierungTuring Sim: Making the USD Schemas Inspector Readable(29.09.2026 um 06:31 Uhr)
••
Intelligence View
⚡ tsecurity.de Intelligence

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…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

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









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);









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);






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.");
}









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









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









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.");
}


Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten C# Type Conversions

Thematisch verwandte Begriffe: Type, Conversions · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

💬 Kommentare werden geladen…
Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-102367 | mall4j through 4.0 contains an insufficient session expiration vulnerab…
Advisory →
tsecurity.de Icon
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag