Freigeben über


Parsing Other Strings

Microsoft Silverlight will reach end of support after October 2021. Learn more.

In addition to parsing strings that represent numbers and dates, you can also parse strings that represent the Boolean and Enum types into values of those types.

Boolean

The Boolean.Parse method converts a string that represents a Boolean value into a Boolean value. This method is not case-sensitive and can successfully parse a string that contains "True" or "False". The Boolean.Parse method can also parse strings that are surrounded by empty spaces (also called white spaces). If any other string is passed, a FormatException is thrown.

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

Dim myString As String = "True"
Dim myBool As Boolean = Boolean.Parse(myString)
outputBlock.Text &= myBool & vbCrLf
' The example displays the following output:
'      True
string myString = "True";
bool myBool = bool.Parse(myString);
outputBlock.Text += myBool + "\n";
// The example displays the following output:
//       True

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 that indicates whether the parsing 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. 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 DayOfWeek enumeration is initialized to Thursday from a string.

Dim myString As String = "Thursday"
Dim myDays as DayOfWeek = _
    CType([Enum].Parse(GetType(DayOfWeek), myString, True), DayOfWeek)
outputBlock.Text &= myDays.ToString() & vbCrLf
' The example displays the following output:
'       Thursday
string myString = "Thursday";
DayOfWeek myDays = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), myString, true);
outputBlock.Text += myDays + "\n";
// The example displays the following output: 
//       Thursday