Permalink
Fetching contributors…
Cannot retrieve contributors at this time
55 lines (45 sloc) 3.75 KB
title ms.custom ms.date ms.prod ms.reviewer ms.suite ms.technology ms.tgt_pltfrm ms.topic helpviewer_keywords ms.assetid caps.latest.revision author ms.author manager
Parsing Other Strings in .NET
03/30/2017
.net
dotnet-standard
article
Char data type, parsing strings
enumerations [.NET Framework], parsing strings
base types, parsing strings
parsing strings, other strings
Boolean data type, parsing strings
d139bc00-3c4e-4d78-ac9a-5c951b258d28
15
rpetrusha
ronpet
wpickett

Parsing Other Strings in .NET

In addition to numeric and xref:System.DateTime strings, you can also parse strings that represent the types xref:System.Char, xref:System.Boolean, and xref:System.Enum into data types.

Char

The static parse method associated with the Char data type is useful for converting a string that contains a single character into its Unicode value. The following code example parses a string into a Unicode character.

[!code-cppConceptual.String.Parse#2] [!code-csharpConceptual.String.Parse#2] [!code-vbConceptual.String.Parse#2]

Boolean

The Boolean data type contains a Parse method that you can use to convert a string that represents a Boolean value into an actual Boolean type. This method is not case-sensitive and can successfully parse a string containing "True" or "False." The Parse method associated with the Boolean type can also parse strings that are surrounded by white spaces. If any other string is passed, a xref:System.FormatException is thrown.

The following code example uses the Parse method to convert a string into a Boolean value.

[!code-cppConceptual.String.Parse#3] [!code-csharpConceptual.String.Parse#3] [!code-vbConceptual.String.Parse#3]

Enumeration

You can use the static Parse method to initialize an enumeration type to the value of a string. This method accepts the enumeration type you are parsing, the string to parse, and an optional Boolean flag indicating whether or not the parse is case-sensitive. The string you are parsing can contain several values separated by commas, which can be preceded or followed by one or more empty spaces (also called white spaces). When the string contains multiple values, the value of the returned object is the value of all specified values combined with a bitwise OR operation.

The following example uses the Parse method to convert a string representation into an enumeration value. The xref:System.DayOfWeek enumeration is initialized to Thursday from a string.

[!code-cppConceptual.String.Parse#4] [!code-csharpConceptual.String.Parse#4] [!code-vbConceptual.String.Parse#4]

See Also

Parsing Strings
Formatting Types
Type Conversion in the .NET