Intro
This post is an addition to one of the lectures from our C# Masterclass. It also contains the course code and extra code samples.
Parsing strings in C# is a common task for software developers, as strings often need to be converted into other data types in order to be used effectively in a program. In this article, we will explore the different methods for string parsing in C#, including using the Parse
method, the TryParse
method, and custom parsing methods.
Parse and TryParse methods
The Parse
method is one of the most straightforward methods for string parsing in C#. The Parse
method takes a string as input and converts it into a value of a specified data type. For example, you can use the int.Parse
method to convert a string into an integer:
string stringToParse = "10"; int result = int.Parse(stringToParse);
One potential issue with the Parse
method is that it can throw an exception if the string being parsed is not in the correct format for the specified data type. To avoid this issue, you can use the TryParse
method instead. The TryParse
method works similarly to the Parse
method, but returns a Boolean value indicating whether the string was successfully parsed or not. This method can be used to check if a string is in the correct format before attempting to parse it:
string stringToParse = "10"; int result; if (int.TryParse(stringToParse, out result)) { // the string was successfully parsed into an integer Console.WriteLine(result); // result is 10 } else { // the string was not in the correct format for an integer }
Source code for the lecture
string oneNumberInString = "15"; string anotherNumberInString = "13"; int oneNumber = int.Parse(oneNumberInString); int anotherNumber = int.Parse(anotherNumberInString); int result = oneNumber + anotherNumber; Console.WriteLine("{0} + {1} = {2}", oneNumber, anotherNumber, result);
If you want to skyrocket your C# career, check out our powerful ASP.NET FULL-STACK WEB DEVELOPMENT COURSE, which also covers test-driven development and C# software architecture.