C#:C# Type Casting: int.TryParse, as, and is Pattern Matching
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:

ParameterTypeDescription
TryParseMethodReturns boolean indicating parse success without throwing.
is PatternC# FeatureTests type and binds new typed variable in one step.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler