C#•Type Casting
C# Type Casting: int.TryParse, as, and is Pattern Matching
Learn defensive parsing with TryParse and safe downcasting using modern C# is type patterns.
Syntax
if (int.TryParse(str, out int val)) {}
if (obj is string s) {}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| TryParse | Method | Returns boolean indicating parse success without throwing. |
| is Pattern | C# Feature | Tests type and binds new typed variable in one step. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C# locally:
using System;
public class Program {
public static void Main() {
// 1. Safe TryParse (never throws exception)
string rawPort = "8080";
if (int.TryParse(rawPort, out int portNumber)) {
Console.WriteLine($"Successfully parsed port: {portNumber}");
}
// 2. Type Pattern Matching with is
object dataPayload = "compilra_secure_session_token";
if (dataPayload is string text) {
Console.WriteLine($"Payload is string (Length: {text.Length}): {text.ToUpper()}");
}
}
}Expected Output:
Successfully parsed port: 8080 Payload is string (Length: 29): COMPILRA_SECURE_SESSION_TOKEN
How It Works: Step-by-Step
- Lines 6-8: int.TryParse parses string into out variable portNumber.
- Lines 12-14: dataPayload is string text tests type and binds text variable.
Key Concepts
- int.TryParse avoids expensive FormatException try/catch overhead.
- C# is pattern matching (obj is Type t) tests and casts simultaneously.
Common Mistake: Using int.Parse() on untrusted user input without try/catch
int.Parse throws FormatException on invalid inputs; use int.TryParse instead.
❌ Incorrect
int x = int.Parse("abc"); // Unhandled FormatException crash!✅ Correct
if (int.TryParse("abc", out int x)) { /* Safe */ }Related C# Tutorials & Compiler
C# Strongly Typed Implicit Var Assignments and Data Types
Master C# static typing with implicit var inference, primitive types (int, double, decimal, bool), and formatting specifiers.
C# Operators: Null-Conditional (?.) and Null-Coalescing (??)
Master C# operators, arithmetic, comparison, null-conditional (?.), and null-coalescing (??).
C# Pattern Matching Switch Statements and Expressions
Implement modern C# pattern matching switch expressions (=>) with relational ranges, logical combinators (and/or), and discard guards.
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.