C# Type Casting

Implicit Casting

C# automatically converts smaller types to larger compatible types:

int num = 42;
double result = num;  // implicitly equal to 42.0, but will print 42
Console.WriteLine(result);

Explicit Casting

Use parentheses to cast when there may be a loss of data:

Loading...
Output:

Convert Class

Use the Convert class to safely convert between types:

Loading...
Output:

Parsing Strings

Use int.Parse() or double.Parse() to convert from strings:

Loading...
Output:

Use TryParse() to avoid crashes on bad input:

Loading...
Output:

Casting Errors

Not all types can be cast. For example, casting a string directly to int without parsing will throw an exception.

Loading...
Output:

Practice Prompt

What does this print?

A. 10
B. 10.0
C. Error
Loading...
Output:

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic