C# Type Conversions
Distinguish an explicit numeric cast from parsing and handle a narrowing overflow deliberately.
How it works
Numeric conversion changes a value’s representation. Some conversions are implicit because the language allows them safely enough for that type relation; others require an explicit cast. A cast is not input parsing and does not validate a business domain. Converting floating values to integral types also loses a fractional part. Use checked for an operation whose overflow must be reported, and use TryParse for outside text. Keep the original value until conversion and domain validation succeed.
Run it locally
Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-buildUse the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.
Example
using System;
internal static class Program
{
private static void Main(string[] args)
{
double hours = 3.75;
int wholeHours = (int)hours;
Console.WriteLine($"Whole hours: {wholeHours}");
try
{
long incoming = (long)int.MaxValue + 1;
int narrowed = checked((int)incoming);
Console.WriteLine(narrowed);
}
catch (OverflowException) { Console.WriteLine("Count is outside int range"); }
}
}
Expected result
Whole hours: 3
Count is outside int range
The finite in-range floating fixture truncates toward zero. The long value cannot fit in int, so the checked conversion throws before a narrowed value is used. A count that fits int can still exceed a session’s capacity, requiring a separate domain check. Exception handling is appropriate here to demonstrate checked conversion; ordinary user validation can use a nonthrowing result.
Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.