0% found this document useful (0 votes)
17 views3 pages

CSharp Data Conversion Cheat Sheet

This cheat sheet outlines various methods for data conversion in C#, including TryParse, Parse, Convert class, casting, and implicit conversion. Each method is categorized by safety, rounding behavior, and best use cases, providing examples for clarity. It also includes a quick reference table for choosing the appropriate method based on specific scenarios.

Uploaded by

abhinav.be046
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views3 pages

CSharp Data Conversion Cheat Sheet

This cheat sheet outlines various methods for data conversion in C#, including TryParse, Parse, Convert class, casting, and implicit conversion. Each method is categorized by safety, rounding behavior, and best use cases, providing examples for clarity. It also includes a quick reference table for choosing the appropriate method based on specific scenarios.

Uploaded by

abhinav.be046
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C# Data Conversion Cheat Sheet

1. TryParse()

- Safe: Never throws exceptions

- No rounding - only converts valid strings

- Best for: User input (like forms, console input)

- Returns: true or false

Example:

int.TryParse("123", out int result); // result = 123

int.TryParse("abc", out int result); // result = 0, returns false

2. Parse()

- Unsafe: Throws exception if input is invalid

- Precise: No rounding or truncating

- Best for: Trusted or internal data

Example:

int.Parse("123"); // returns 123

int.Parse("abc"); // throws FormatException

3. Convert Class (Convert.ToInt32, etc.)

- Safe (handles null)

- Rounding: Rounds decimal values

- Best for: General conversions

Example:
Convert.ToInt32(4.7); // returns 5

Convert.ToInt32(null); // returns 0, no crash

Convert.ToInt32("abc"); // throws FormatException

4. Casting (Explicit Conversion)

- Unsafe: Can truncate data

- No rounding, just cuts decimal part

- Best for: Performance, known-safe conversions

Example:

int number = (int)4.9; // result = 4 (truncated)

float small = (float)123; // Implicit OK (int to float)

5. Implicit Conversion

- Safe: Done automatically by compiler (if no data loss)

- No need for cast

Example:

int a = 100;

long b = a; // Implicit conversion, safe

6. When to Use What?

Scenario | Best Choice

-------------------------------- | ----------------------

User form input | TryParse()

Trusted string (e.g., config) | Parse()

Convert decimal to int safely | Convert.ToInt32()


Need speed, truncate is okay | Casting (int)

No conversion risk | Implicit

You might also like