Type Conversion
Type Conversion/ Casting in C#?
C# supports four primary categories of type conversion
Implicit Conversions (Automatic)
Implicit conversion happens automatically when you convert a smaller data type into a larger data type, or a derived class into a base class. This process is entirely type-safe, and no data is lost during the operation
Example
double d = x;
// implicit casting
Console.WriteLine(d);
Explicit Type Casting
Explicit conversion is a manual step required when converting a larger data type to a smaller data type (narrowing), or a base class to a derived class. This is done using a cast operator (the target type in parentheses). This conversion carries a risk of data loss or truncation.
Example
// explicit casting
int x = (int)d;
Console.WriteLine(x);
Invalid Implicit Conversion
double d = 5.8;
// Error
a = d;
Error: Cannot implicitly convert double to int.
Parsing (String to Numeric)
When dealing with incompatible types, such as converting a string to a number, direct casting will not work. Instead, you must use parsing methods.
-
.Parse(): Throws a runtime exception if the string cannot be successfully converted.
-
.TryParse(): Safely attempts the conversion, returning a boolean indicating success or failure without crashing the program.
Example
// Using Parse (Thows exception if textAge is invalid)
int age1 = int.Parse(textAge);
// Using TryParse (Recommended for safety)
bool success = int.TryParse(textAge, out int age2);
Conversion Classes
The built-in System.Convert utility class provides a broad set of static methods to convert between base data types. Unlike standard casting, Convert handles null values gracefully (returning default values instead of failing) and rounds floating-point numbers instead of truncating them.
int number = Convert.ToInt32(textValue); // Converts string to a 32-bit int
double exactPrice = 19.99;
int roundedPrice = Convert.ToInt32(exactPrice); // Outputs: 20 (Rounds the number)
Direct Comparison: Parse vs TryParse vs Convert
| Feature | int.Parse(str) | int.TryParse(str, out val) | Convert.ToInt32(obj) |
|---|---|---|---|
| Input Type | String only | String only | Supports multiple object types (string, double, bool, etc.) |
| If Input is null | Throws ArgumentNullException | Returns false (no error thrown) | Throws FormatException |
| Best Used For | Guaranteed valid strings | User inputs / Unpredictable strings | Converting non-string types or handling nulls safely |
Safe Reference Type Conversions (as and is)
When dealing with objects and inheritance, throwing standard exceptions can ruin performance. C# offers alternative keywords for smooth object type-casting
-
is keyword: Checks if an object is compatible with a given type and returns a boolean.
-
as keyword: Attempts a conversion; if the conversion fails, it returns null instead of crashing
// Using 'is' with a pattern declaration
if (greeting is string text) {
Console.WriteLine(text.Length);
}
// Using 'as'
string text2 = greeting as string;