Byte.TryParse Method

Definition

Tries to convert the string representation of a number to its Byte equivalent, and returns a value that indicates whether the conversion succeeded.

Overloads

TryParse(String, Byte)

Tries to convert the string representation of a number to its Byte equivalent, and returns a value that indicates whether the conversion succeeded.

TryParse(String, NumberStyles, IFormatProvider, Byte)

Converts the string representation of a number in a specified style and culture-specific format to its Byte equivalent. A return value indicates whether the conversion succeeded or failed.

TryParse(String, Byte)

Tries to convert the string representation of a number to its Byte equivalent, and returns a value that indicates whether the conversion succeeded.

public static bool TryParse (string s, out byte result);
Parameters
s
String

A string that contains a number to convert. The string is interpreted using the Integer style.

result
Byte

When this method returns, contains the Byte value equivalent to the number contained in s if the conversion succeeded, or zero if the conversion failed. This parameter is passed uninitialized; any value originally supplied in result will be overwritten.

Returns

true if s was converted successfully; otherwise, false.

Examples

The following example calls the TryParse(String, Byte) method with a number of different string values.

using namespace System;

void main()
{
   array<String^>^ byteStrings = gcnew array<String^> { nullptr, String::Empty, 
                                                        "1024", "100.1", "100", 
                                                        "+100", "-100", "000000000000000100", 
                                                        "00,100", "   20   ", "FF", "0x1F" };
   Byte byteValue;
   for each (String^ byteString in byteStrings) {
      bool result = Byte::TryParse(byteString, byteValue);
      if (result)
         Console::WriteLine("Converted '{0}' to {1}", 
                            byteString, byteValue);
      else
         Console::WriteLine("Attempted conversion of '{0}' failed.", 
                            byteString);
   }
}
// The example displays the following output:
//       Attempted conversion of '' failed.
//       Attempted conversion of '' failed.`
//       Attempted conversion of '1024' failed.
//       Attempted conversion of '100.1' failed.
//       Converted '100' to 100
//       Converted '+100' to 100
//       Attempted conversion of '-100' failed.
//       Converted '000000000000000100' to 100
//       Attempted conversion of '00,100' failed.
//       Converted '   20   ' to 20
//       Attempted conversion of 'FF' failed.
//       Attempted conversion of '0x1F' failed.}
using System;

public class ByteConversion
{
   public static void Main()
   {
      string byteString = null;
      CallTryParse(byteString);
      
      byteString = String.Empty;
      CallTryParse(byteString);
      
      byteString = "1024";
      CallTryParse(byteString);
      
      byteString = "100.1";
      CallTryParse(byteString);
      
      byteString = "100";
      CallTryParse(byteString);
      
      byteString = "+100";
      CallTryParse(byteString);
      
      byteString = "-100";
      CallTryParse(byteString);
      
      byteString = "000000000000000100";
      CallTryParse(byteString);
      
      byteString = "00,100";
      CallTryParse(byteString);
      
      byteString = "   20   ";
      CallTryParse(byteString);
      
      byteString = "FF";
      CallTryParse(byteString);
      
      byteString = "0x1F";
      CallTryParse(byteString);
   }

   private static void CallTryParse(string stringToConvert)
   {  
      byte byteValue; 
      bool result = Byte.TryParse(stringToConvert, out byteValue);
      if (result)
      {
         Console.WriteLine("Converted '{0}' to {1}", 
                        stringToConvert, byteValue);
      }
      else
      {
         if (stringToConvert == null) stringToConvert = "";
         Console.WriteLine("Attempted conversion of '{0}' failed.", 
                           stringToConvert.ToString());
      }
   }    
}
// The example displays the following output to the console:
//       Attempted conversion of '' failed.
//       Attempted conversion of '' failed.
//       Attempted conversion of '1024' failed.
//       Attempted conversion of '100.1' failed.
//       Converted '100' to 100
//       Converted '+100' to 100
//       Attempted conversion of '-100' failed.
//       Converted '000000000000000100' to 100
//       Attempted conversion of '00,100' failed.
//       Converted '   20   ' to 20
//       Attempted conversion of 'FF' failed.
//       Attempted conversion of '0x1F' failed.
Module ByteConversion
   Public Sub Main()
      Dim byteString As String = Nothing
      CallTryParse(byteString)
      
      byteString = String.Empty
      CallTryParse(byteString)
      
      byteString = "1024"
      CallTryParse(byteString)
      
      byteString = "100.1"
      CallTryParse(byteString)
      
      byteString = "100"
      CallTryParse(byteString)
      
      byteString = "+100"
      CallTryParse(byteString)
      
      byteString = "-100"
      CallTryParse(byteString)
      
      byteString = "000000000000000100"
      CallTryParse(byteString)
      
      byteString = "00,100"      
      CallTryParse(byteString)
      
      byteString = "   20   "
      CallTryParse(byteString)
      
      byteString = "FF"
      CallTryParse(byteString)
      
      byteString = "0x1F"
      CallTryParse(byteString)
   End Sub
   
   Private Sub CallTryParse(stringToConvert As String)  
      Dim byteValue As Byte
      Dim result As Boolean = Byte.TryParse(stringToConvert, byteValue)
      If result Then
         Console.WriteLine("Converted '{0}' to {1}", _
                        stringToConvert, byteValue)
      Else
         If stringToConvert Is Nothing Then stringToConvert = ""
         Console.WriteLine("Attempted conversion of '{0}' failed.", _
                           stringToConvert.ToString())
      End If                        
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversion of '' failed.
'       Attempted conversion of '' failed.
'       Attempted conversion of '1024' failed.
'       Attempted conversion of '100.1' failed.
'       Converted '100' to 100
'       Converted '+100' to 100
'       Attempted conversion of '-100' failed.
'       Converted '000000000000000100' to 100
'       Attempted conversion of '00,100' failed.
'       Converted '   20   ' to 20
'       Attempted conversion of 'FF' failed.
'       Attempted conversion of '0x1F' failed.

Remarks

The conversion fails and the method returns false if the s parameter is not in the correct format, if it is null or String.Empty, or if it represents a number less than MinValue or greater than MaxValue.

The Byte.TryParse(String, Byte) method is similar to the Byte.Parse(String) method, except that TryParse(String, Byte) does not throw an exception if the conversion fails.

The s parameter should be the string representation of a number in the following form:

[ws][sign]digits[ws]  

Elements in square brackets ([ and ]) are optional. The following table describes each element.

Element Description
ws Optional white space.
sign An optional positive sign, as specified by the NumberFormatInfo.PositiveSign property of the current culture.
digits A sequence of decimal digits that range from 0 to 9.

The s parameter is interpreted using the Integer style. In addition to the byte value's decimal digits, only leading and trailing spaces together with a leading sign are allowed. (If the sign is present, it must be a positive sign or the method throws an OverflowException.) To explicitly define the style elements together with the culture-specific formatting information that can be present in s, use the Byte.Parse(String, NumberStyles, IFormatProvider) method.

The s parameter is parsed using the formatting information in a NumberFormatInfo object for the current culture. For more information, see NumberFormatInfo.CurrentInfo.

This overload of the Byte.TryParse(String, Byte) method interprets all digits in the s parameter as decimal digits. To parse the string representation of a hexadecimal number, call the Byte.TryParse(String, NumberStyles, IFormatProvider, Byte) overload.

TryParse(String, NumberStyles, IFormatProvider, Byte)

Converts the string representation of a number in a specified style and culture-specific format to its Byte equivalent. A return value indicates whether the conversion succeeded or failed.

public static bool TryParse (string s, System.Globalization.NumberStyles style, IFormatProvider provider, out byte result);
Parameters
s
String

A string containing a number to convert. The string is interpreted using the style specified by style.

style
NumberStyles

A bitwise combination of enumeration values that indicates the style elements that can be present in s. A typical value to specify is Integer.

provider
IFormatProvider

An object that supplies culture-specific formatting information about s. If provider is null, the thread current culture is used.

result
Byte

When this method returns, contains the 8-bit unsigned integer value equivalent to the number contained in s if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null or Empty, is not of the correct format, or represents a number less than MinValue or greater than MaxValue. This parameter is passed uninitialized; any value originally supplied in result will be overwritten.

Returns

true if s was converted successfully; otherwise, false.

Exceptions

style is not a NumberStyles value.

-or-

style is not a combination of AllowHexSpecifier and HexNumber values.

Examples

The following example calls the TryParse(String, NumberStyles, IFormatProvider, Byte) method with a number of different string values.

using namespace System;
using namespace System::Globalization;

void CallTryParse(String^ byteString, NumberStyles styles);

void main()
{
   String^ byteString; 
   NumberStyles styles;

   byteString = "1024";
   styles = NumberStyles::Integer;
   CallTryParse(byteString, styles);

   byteString = "100.1";
   styles = NumberStyles::Integer | NumberStyles::AllowDecimalPoint;
   CallTryParse(byteString, styles);

   byteString = "100.0";
   CallTryParse(byteString, styles);

   byteString = "+100";
   styles = NumberStyles::Integer | NumberStyles::AllowLeadingSign 
            | NumberStyles::AllowTrailingSign;
   CallTryParse(byteString, styles);

   byteString = "-100";
   CallTryParse(byteString, styles);

   byteString = "000000000000000100";
   CallTryParse(byteString, styles);

   byteString = "00,100";
   styles = NumberStyles::Integer | NumberStyles::AllowThousands;
   CallTryParse(byteString, styles);

   byteString = "2E+3   ";
   styles = NumberStyles::Integer | NumberStyles::AllowExponent;
   CallTryParse(byteString, styles);

   byteString = "FF";
   styles = NumberStyles::HexNumber;
   CallTryParse(byteString, styles);

   byteString = "0x1F";
   CallTryParse(byteString, styles);
}

void CallTryParse(String^ stringToConvert, NumberStyles styles)
{  
   Byte byteValue;
   bool result = Byte::TryParse(stringToConvert, styles, 
                                 (IFormatProvider^) nullptr , byteValue);
   if (result)
      Console::WriteLine("Converted '{0}' to {1}", 
                     stringToConvert, byteValue);
   else
      Console::WriteLine("Attempted conversion of '{0}' failed.", 
                        stringToConvert);
}
// The example displays the following output:
//       Attempted conversion of '1024' failed.
//       Attempted conversion of '100.1' failed.
//       Converted '100.0' to 100
//       Converted '+100' to 100
//       Attempted conversion of '-100' failed.
//       Converted '000000000000000100' to 100
//       Converted '00,100' to 100
//       Attempted conversion of '2E+3   ' failed.
//       Converted 'FF' to 255
//       Attempted conversion of '0x1F' failed.}
using System;
using System.Globalization;

public class ByteConversion2
{
   public static void Main()
   {
      string byteString; 
      NumberStyles styles;
      
      byteString = "1024";
      styles = NumberStyles.Integer;
      CallTryParse(byteString, styles);
      
      byteString = "100.1";
      styles = NumberStyles.Integer | NumberStyles.AllowDecimalPoint;
      CallTryParse(byteString, styles);
      
      byteString = "100.0";
      CallTryParse(byteString, styles);
      
      byteString = "+100";
      styles = NumberStyles.Integer | NumberStyles.AllowLeadingSign 
               | NumberStyles.AllowTrailingSign;
      CallTryParse(byteString, styles);
      
      byteString = "-100";
      CallTryParse(byteString, styles);
      
      byteString = "000000000000000100";
      CallTryParse(byteString, styles);
      
      byteString = "00,100";
      styles = NumberStyles.Integer | NumberStyles.AllowThousands;
      CallTryParse(byteString, styles);
      
      byteString = "2E+3   ";
      styles = NumberStyles.Integer | NumberStyles.AllowExponent;
      CallTryParse(byteString, styles);
      
      byteString = "FF";
      styles = NumberStyles.HexNumber;
      CallTryParse(byteString, styles);
      
      byteString = "0x1F";
      CallTryParse(byteString, styles);
   }

   private static void CallTryParse(string stringToConvert, NumberStyles styles)
   {  
      Byte byteValue;
      bool result = Byte.TryParse(stringToConvert, styles, 
                                  null as IFormatProvider, out byteValue);
      if (result)
         Console.WriteLine("Converted '{0}' to {1}", 
                        stringToConvert, byteValue);
      else
         Console.WriteLine("Attempted conversion of '{0}' failed.", 
                           stringToConvert.ToString());
   }
}
// The example displays the following output to the console:
//       Attempted conversion of '1024' failed.
//       Attempted conversion of '100.1' failed.
//       Converted '100.0' to 100
//       Converted '+100' to 100
//       Attempted conversion of '-100' failed.
//       Converted '000000000000000100' to 100
//       Converted '00,100' to 100
//       Attempted conversion of '2E+3   ' failed.
//       Converted 'FF' to 255
//       Attempted conversion of '0x1F' failed.
Imports System.Globalization

Module ByteConversion2
   Public Sub Main()
      Dim byteString As String 
      Dim styles As NumberStyles
      
      byteString = "1024"
      styles = NumberStyles.Integer
      CallTryParse(byteString, styles)
      
      byteString = "100.1"
      styles = NumberStyles.Integer Or NumberStyles.AllowDecimalPoint
      CallTryParse(byteString, styles)
      
      byteString = "100.0"
      CallTryParse(byteString, styles)
      
      byteString = "+100"
      styles = NumberStyles.Integer Or NumberStyles.AllowLeadingSign _
               Or NumberStyles.AllowTrailingSign
      CallTryParse(byteString, styles)
      
      byteString = "-100"
      CallTryParse(byteString, styles)
      
      byteString = "000000000000000100"
      CallTryParse(byteString, styles)
      
      byteString = "00,100"      
      styles = NumberStyles.Integer Or NumberStyles.AllowThousands
      CallTryParse(byteString, styles)
      
      byteString = "2E+3   "
      styles = NumberStyles.Integer Or NumberStyles.AllowExponent
      CallTryParse(byteString, styles)
      
      byteString = "FF"
      styles = NumberStyles.HexNumber
      CallTryParse(byteString, styles)
      
      byteString = "0x1F"
      CallTryParse(byteString, styles)
   End Sub
   
   Private Sub CallTryParse(stringToConvert As String, styles As NumberStyles)  
      Dim byteValue As Byte
      Dim result As Boolean = Byte.TryParse(stringToConvert, styles, Nothing, _
                                            byteValue)
      If result Then
         Console.WriteLine("Converted '{0}' to {1}", _
                        stringToConvert, byteValue)
      Else
         If stringToConvert Is Nothing Then stringToConvert = ""
         Console.WriteLine("Attempted conversion of '{0}' failed.", _
                           stringToConvert.ToString())
      End If                        
   End Sub
End Module
' The example displays the following output to the console:
'       Attempted conversion of '1024' failed.
'       Attempted conversion of '100.1' failed.
'       Converted '100.0' to 100
'       Converted '+100' to 100
'       Attempted conversion of '-100' failed.
'       Converted '000000000000000100' to 100
'       Converted '00,100' to 100
'       Attempted conversion of '2E+3   ' failed.
'       Converted 'FF' to 255
'       Attempted conversion of '0x1F' failed.

Remarks

The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails.

The s parameter is parsed using the formatting information in a NumberFormatInfo object supplied by the provider parameter.

The style parameter defines the style elements (such as white space or the positive sign) that are allowed in the s parameter for the parse operation to succeed. It must be a combination of bit flags from the NumberStyles enumeration. Depending on the value of style, the s parameter may include the following elements:

[ws][$][sign]digits[.fractional_digits][e[sign]digits][ws]

Or, if the style parameter includes AllowHexSpecifier:

[ws]hexdigits[ws]

Elements in square brackets ( [ and ] ) are optional. The following table describes each element.

Element Description
ws Optional white space. White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag, or at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$ A culture-specific currency symbol. Its position in the string is defined by the NumberFormatInfo.CurrencyPositivePattern property of the NumberFormatInfo object returned by the GetFormat method of the provider parameter. The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
sign An optional positive sign. (The parse operation fails if a negative sign is present in s.) The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, or at the end of s if style includes the NumberStyles.AllowTrailingSign flag.
digits A sequence of digits from 0 through 9.
. A culture-specific decimal point symbol. The decimal point symbol of the culture specified by provider can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional_digits One or more occurrences of the digit 0. Fractional digits can appear in s only if style includes the NumberStyles.AllowDecimalPoint flag.
e The e or E character, which indicates that the value is represented in exponential notation. The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
hexdigits A sequence of hexadecimal digits from 0 through f, or 0 through F.

A string with decimal digits only (which corresponds to the NumberStyles.None style) always parses successfully. Most of the remaining NumberStyles members control elements that may be but are not required to be present in this input string. The following table indicates how individual NumberStyles members affect the elements that may be present in s.

Non-composite NumberStyles values Elements permitted in s in addition to digits
NumberStyles.None Decimal digits only.
NumberStyles.AllowDecimalPoint The . and fractional_digits elements. However, fractional_digits must consist of only one or more 0 digits or the method returns false.
NumberStyles.AllowExponent The s parameter can also use exponential notation. If s represents a number in exponential notation, it must represent an integer within the range of the Byte data type without a non-zero, fractional component.
NumberStyles.AllowLeadingWhite The ws element at the beginning of s.
NumberStyles.AllowTrailingWhite The ws element at the end of s.
NumberStyles.AllowLeadingSign A positive sign can appear before digits.
NumberStyles.AllowTrailingSign A positive sign can appear after digits.
NumberStyles.AllowParentheses Although this flag is supported, the method returns false if parentheses are present in s.
NumberStyles.AllowThousands Although the group separator symbol can appear in s, it can be preceded by only one or more 0 digits.
NumberStyles.AllowCurrencySymbol The $ element.

If the NumberStyles.AllowHexSpecifier flag is used, s must be a hexadecimal value without a prefix. For example, "F3" parses successfully, but "0xF3" does not. The only other flags that can be present in style are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (The NumberStyles enumeration has a composite number style, NumberStyles.HexNumber, that includes both white space flags.)

The provider parameter is an IFormatProvider implementation, such as a CultureInfo object or a NumberFormatInfo object, whose GetFormat method returns a NumberFormatInfo object. The NumberFormatInfo object provides culture-specific information about the format of s.

See Also

Applies to