C#.NET: Correct ways to convert a String to an int (assume s = '123'). Select all valid C# approaches.

Difficulty: Easy

Correct Answer: 2, 3, 4

Explanation:


Introduction / Context:
Converting text to numeric types is routine. In C#, several standard methods exist to convert a numeric string to an int, each with different behavior for invalid input.



Given Data / Assumptions:

  • String s = '123'; and int i;
  • Evaluate: casting, int.Parse, Int32.Parse, Convert.ToInt32, CInt.


Concept / Approach:
int.Parse and Int32.Parse are equivalent and parse a string containing digits into an integer (throwing on invalid format). Convert.ToInt32 also parses strings and handles null differently (returns 0 for null). Direct casting from string to int is not allowed. CInt is a VB keyword, not valid C# syntax.



Step-by-Step Solution:

Attempt i = (int)s; → invalid in C#.Use i = int.Parse(s); → valid.Use i = Int32.Parse(s); → valid.Use i = Convert.ToInt32(s); → valid.Use i = CInt(s); → invalid in C#.


Verification / Alternative check:
For safe parsing, int.TryParse(s, out i) avoids exceptions on bad input and returns a boolean.



Why Other Options Are Wrong:
Any combination including 1 or 5 is incorrect because casting a string to int is illegal and CInt is not a C# construct.



Common Pitfalls:
Confusing C# with VB syntax; forgetting to handle invalid inputs and culture-specific formats.



Final Answer:
2, 3, 4

More Questions from Strings

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion