Edit

Share via


SByte.Parse Method

Definition

Converts the string representation of a number to its 8-bit signed integer equivalent.

Overloads

Parse(String, NumberStyles, IFormatProvider)

Converts the string representation of a number that is in a specified style and culture-specific format to its 8-bit signed equivalent.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converts the span representation of a number that is in a specified style and culture-specific format to its 8-bit signed equivalent.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Parses a span of UTF-8 characters into a value.

Parse(String, IFormatProvider)

Converts the string representation of a number in a specified culture-specific format to its 8-bit signed integer equivalent.

Parse(String)

Converts the string representation of a number to its 8-bit signed integer equivalent.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Parses a span of characters into a value.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Parses a span of UTF-8 characters into a value.

Parse(String, NumberStyles)

Converts the string representation of a number in a specified style to its 8-bit signed integer equivalent.

Parse(String, NumberStyles, IFormatProvider)

Source:
SByte.cs
Source:
SByte.cs
Source:
SByte.cs

Important

This API is not CLS-compliant.

CLS-compliant alternative
System.Int16.Parse(String, NumberStyles, IFormatProvider)

Converts the string representation of a number that is in a specified style and culture-specific format to its 8-bit signed equivalent.

public:
 static System::SByte Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
 static System::SByte Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<System::SByte>::Parse;
[System.CLSCompliant(false)]
public static sbyte Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static sbyte Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static sbyte Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> sbyte
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> sbyte
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As SByte

Parameters

s
String

A string that contains the number to convert. The string is interpreted by using the style specified by style.

style
NumberStyles

A bitwise combination of the 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.

Returns

An 8-bit signed byte value that is equivalent to the number specified in the s parameter.

Implements

Attributes

Exceptions

style is not a NumberStyles value.

-or-

style is not a combination of AllowHexSpecifier and HexNumber.

s is not in a format that is compliant with style.

s represents a number that is less than SByte.MinValue or greater than SByte.MaxValue.

-or-

s includes non-zero, fractional digits.

Examples

The following example illustrates the use of the Parse(String, NumberStyles, IFormatProvider) method to convert various string representations of numbers to signed integer values.

using System;
using System.Globalization;

public class SByteConversion
{
   NumberFormatInfo provider = NumberFormatInfo.CurrentInfo;

   public static void Main()
   {
      string stringValue;
      NumberStyles style;

      stringValue = "   123   ";
      style = NumberStyles.None;     
      CallParseOperation(stringValue, style);
      
      stringValue = "000,000,123";
      style = NumberStyles.Integer | NumberStyles.AllowThousands;
      CallParseOperation(stringValue, style);
      
      stringValue = "-100";
      style = NumberStyles.AllowLeadingSign;
      CallParseOperation(stringValue, style);
      
      stringValue = "100-";
      style = NumberStyles.AllowLeadingSign;
      CallParseOperation(stringValue, style);
      
      stringValue = "100-";
      style = NumberStyles.AllowTrailingSign;
      CallParseOperation(stringValue, style);
      
      stringValue = "$100";
      style = NumberStyles.AllowCurrencySymbol;
      CallParseOperation(stringValue, style);
      
      style = NumberStyles.Integer;
      CallParseOperation(stringValue, style);
      
      style = NumberStyles.AllowDecimalPoint;
      CallParseOperation("100.0", style);
      
      stringValue = "1e02";
      style = NumberStyles.AllowExponent;
      CallParseOperation(stringValue, style);
      
      stringValue = "(100)";
      style = NumberStyles.AllowParentheses;
      CallParseOperation(stringValue, style);
   }
   
   private static void CallParseOperation(string stringValue, 
                                          NumberStyles style)
   {                                          
      sbyte number;
      
      if (stringValue == null)
         Console.WriteLine("Cannot parse a null string...");
         
      try
      {
         number = sbyte.Parse(stringValue, style);
         Console.WriteLine("SByte.Parse('{0}', {1})) = {2}", 
                           stringValue, style, number);   
      }
      catch (FormatException)
      {
         Console.WriteLine("'{0}' and {1} throw a FormatException", 
                           stringValue, style);   
      }      
      catch (OverflowException)
      {
         Console.WriteLine("'{0}' is outside the range of a signed byte",
                           stringValue);
      }
   }
}
// The example displays the following information to the console:
//       '   123   ' and None throw a FormatException
//       SByte.Parse('000,000,123', Integer, AllowThousands)) = 123
//       SByte.Parse('-100', AllowLeadingSign)) = -100
//       '100-' and AllowLeadingSign throw a FormatException
//       SByte.Parse('100-', AllowTrailingSign)) = -100
//       SByte.Parse('$100', AllowCurrencySymbol)) = 100
//       '$100' and Integer throw a FormatException
//       SByte.Parse('100.0', AllowDecimalPoint)) = 100
//       SByte.Parse('1e02', AllowExponent)) = 100
//       SByte.Parse('(100)', AllowParentheses)) = -100
open System
open System.Globalization

let provider = NumberFormatInfo.CurrentInfo
   
let callParseOperation stringValue (style: NumberStyles) =
    if stringValue = null then
        printfn "Cannot parse a null string..."
    else
        try
            let number = SByte.Parse(stringValue, style)
            printfn $"SByte.Parse('{stringValue}', {style})) = {number}" 
        with
        | :? FormatException ->
            printfn $"'{stringValue}' and {style} throw a FormatException"
        | :? OverflowException ->
            printfn $"'{stringValue}' is outside the range of a signed byte"

[<EntryPoint>]
let main _ =
    let stringValue = "   123   "
    let style = NumberStyles.None     
    callParseOperation stringValue style
    
    let stringValue = "000,000,123"
    let style = NumberStyles.Integer ||| NumberStyles.AllowThousands
    callParseOperation stringValue style
    
    let stringValue = "-100"
    let style = NumberStyles.AllowLeadingSign
    callParseOperation stringValue style
    
    let stringValue = "100-"
    let style = NumberStyles.AllowLeadingSign
    callParseOperation stringValue style
    
    let stringValue = "100-"
    let style = NumberStyles.AllowTrailingSign
    callParseOperation stringValue style
    
    let stringValue = "$100"
    let style = NumberStyles.AllowCurrencySymbol
    callParseOperation stringValue style
    
    let style = NumberStyles.Integer
    callParseOperation stringValue style
    
    let style = NumberStyles.AllowDecimalPoint
    callParseOperation "100.0" style
    
    let stringValue = "1e02"
    let style = NumberStyles.AllowExponent
    callParseOperation stringValue style
    
    let stringValue = "(100)"
    let style = NumberStyles.AllowParentheses
    callParseOperation stringValue style
    0

// The example displays the following information to the console:
//       '   123   ' and None throw a FormatException
//       SByte.Parse('000,000,123', Integer, AllowThousands)) = 123
//       SByte.Parse('-100', AllowLeadingSign)) = -100
//       '100-' and AllowLeadingSign throw a FormatException
//       SByte.Parse('100-', AllowTrailingSign)) = -100
//       SByte.Parse('$100', AllowCurrencySymbol)) = 100
//       '$100' and Integer throw a FormatException
//       SByte.Parse('100.0', AllowDecimalPoint)) = 100
//       SByte.Parse('1e02', AllowExponent)) = 100
//       SByte.Parse('(100)', AllowParentheses)) = -100
Imports System.Globalization

Module modMain
   Public Sub Main()
      Dim byteString As String 
      
      byteString = " 123"
      ParseString(byteString, NumberStyles.None)
      ParseString(byteString, NumberStyles.Integer)
      
      byteString = "3A"
      ParseString(byteString, NumberStyles.AllowHexSpecifier) 
      
      byteString = "21"
      ParseString(byteString, NumberStyles.Integer)
      ParseString(byteString, NumberStyles.AllowHexSpecifier)
      
      byteString = "-22"
      ParseString(byteString, NumberStyles.Integer)
      ParseString(byteString, NumberStyles.AllowParentheses)
      
      byteString = "(45)"
      ParseString(byteString, NumberStyles.AllowParentheses)
     
      byteString = "000,000,056"
      ParseString(byteString, NumberStyles.Integer)
      ParseString(byteString, NumberStyles.Integer Or NumberStyles.AllowThousands)
   End Sub
   
   Private Sub ParseString(value As String, style As NumberStyles)
      Dim number As SByte
      
      If value Is Nothing Then Console.WriteLine("Cannot parse a null string...") 
      
      Try
         number = SByte.Parse(value, style, NumberFormatInfo.CurrentInfo)
         Console.WriteLine("SByte.Parse('{0}', {1}) = {2}", value, style, number)   
      Catch e As FormatException
         Console.WriteLine("'{0}' and {1} throw a FormatException", value, style)   
      Catch e As OverflowException
         Console.WriteLine("'{0}' is outside the range of a signed byte",
                           value)
      End Try     
   End Sub
End Module
' The example displays the following information to the console:
'       ' 123' and None throw a FormatException
'       SByte.Parse(" 123", Integer)) = 123
'       SByte.Parse("3A", AllowHexSpecifier)) = 58
'       SByte.Parse("21", Integer)) = 21
'       SByte.Parse("21", AllowHexSpecifier)) = 33
'       SByte.Parse("-22", Integer)) = -22
'       '-22' and AllowParentheses throw a FormatException
'       SByte.Parse("(45)", AllowParentheses)) = -45
'       '000,000,056' and Integer throw a FormatException
'       SByte.Parse("000,000,056", Integer, AllowThousands)) = 56

Remarks

The style parameter defines the style elements (such as white space or the positive or negative sign symbol) 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]exponential_digits][ws]

If style includes AllowHexSpecifier, the s parameter may include the following elements:

[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, and it can appear 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 current culture. The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
sign An optional sign. The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear the end of s if style includes the NumberStyles.AllowTrailingSign flag. Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
digits A sequence of digits from 0 through 9.
. A culture-specific decimal point symbol. The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional_digits One or more occurrences of the digit 0-9 if style includes the NumberStyles.AllowExponent flag, or one or more occurrences of the digit 0 if it does not. 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 (scientific) notation. The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential_digits A sequence of digits from 0 through 9. 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.

Note

Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

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 present, 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 decimal point (.) and fractional_digits elements. However, if style does not include the NumberStyles.AllowExponent flag, fractional_digits must consist of only one or more 0 digits; otherwise, an OverflowException is thrown.
NumberStyles.AllowExponent The "e" or "E" character, which indicates exponential notation, along with exponential_digits.
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 before digits.
NumberStyles.AllowTrailingSign A positive sign after digits.
NumberStyles.AllowParentheses Parentheses before and after digits to indicate a negative value.
NumberStyles.AllowThousands The group separator (,) element. Although the group separator can appear in s, it must be preceded by only one or more 0 digits.
NumberStyles.AllowCurrencySymbol The currency ($) element.

If the NumberStyles.AllowHexSpecifier flag is used, s must be a hexadecimal value. Valid hexadecimal digits are 0-9, a-f, and A-F. The only other flags that can be combined with it are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (The NumberStyles enumeration includes a composite number style, NumberStyles.HexNumber, that includes both white-space flags.)

Note

If the s parameter is the string representation of a hexadecimal number, it cannot be preceded by any decoration (such as 0x or &h) that differentiates it as a hexadecimal number. This causes the parse operation to throw an exception.

If s represents a hexadecimal number, the Parse(String, NumberStyles) method interprets the high-order bit of the byte as a sign bit.

The provider parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of s. There are three ways to use the provider parameter to supply custom formatting information to the parse operation:

  • You can pass the actual NumberFormatInfo object that provides formatting information. (Its implementation of GetFormat simply returns itself.)

  • You can pass a CultureInfo object that specifies the culture whose formatting is to be used. Its NumberFormat property provides formatting information.

  • You can pass a custom IFormatProvider implementation. Its GetFormat method must instantiate and return the NumberFormatInfo object that provides formatting information.

If provider is null, the NumberFormatInfo object for the current culture is used.

Applies to

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Source:
SByte.cs
Source:
SByte.cs
Source:
SByte.cs

Important

This API is not CLS-compliant.

Converts the span representation of a number that is in a specified style and culture-specific format to its 8-bit signed equivalent.

public static sbyte Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
[System.CLSCompliant(false)]
public static sbyte Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider provider = default);
[System.CLSCompliant(false)]
public static sbyte Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> sbyte
[<System.CLSCompliant(false)>]
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> sbyte
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As SByte

Parameters

s
ReadOnlySpan<Char>

A span containing the characters representing the number to convert. The span is interpreted by using the style specified by style.

style
NumberStyles

A bitwise combination of the 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.

Returns

An 8-bit signed byte value that is equivalent to the number specified in the s parameter.

Implements

Attributes

Applies to

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Source:
SByte.cs
Source:
SByte.cs

Parses a span of UTF-8 characters into a value.

public static sbyte Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> sbyte
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As SByte

Parameters

utf8Text
ReadOnlySpan<Byte>

The span of UTF-8 characters to parse.

style
NumberStyles

A bitwise combination of number styles that can be present in utf8Text.

provider
IFormatProvider

An object that provides culture-specific formatting information about utf8Text.

Returns

The result of parsing utf8Text.

Implements

Applies to

Parse(String, IFormatProvider)

Source:
SByte.cs
Source:
SByte.cs
Source:
SByte.cs

Important

This API is not CLS-compliant.

CLS-compliant alternative
System.Int16.Parse(String)

Converts the string representation of a number in a specified culture-specific format to its 8-bit signed integer equivalent.

public:
 static System::SByte Parse(System::String ^ s, IFormatProvider ^ provider);
public:
 static System::SByte Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<System::SByte>::Parse;
[System.CLSCompliant(false)]
public static sbyte Parse (string s, IFormatProvider provider);
public static sbyte Parse (string s, IFormatProvider? provider);
[System.CLSCompliant(false)]
public static sbyte Parse (string s, IFormatProvider? provider);
[<System.CLSCompliant(false)>]
static member Parse : string * IFormatProvider -> sbyte
static member Parse : string * IFormatProvider -> sbyte
Public Shared Function Parse (s As String, provider As IFormatProvider) As SByte

Parameters

s
String

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

provider
IFormatProvider

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

Returns

An 8-bit signed integer that is equivalent to the number specified in s.

Implements

Attributes

Exceptions

s is not in the correct format.

s represents a number less than SByte.MinValue or greater than SByte.MaxValue.

Examples

The following example defines a custom NumberFormatInfo object that defines the tilde (~) as the negative sign. It then parses a number of numeric strings using this custom NumberFormatInfo object as well as a CultureInfo object that represents the invariant culture.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      NumberFormatInfo nf = new NumberFormatInfo();
      nf.NegativeSign = "~"; 
      
      string[] values = { "-103", "+12", "~16", "  1", "~255" };
      IFormatProvider[] providers = { nf, CultureInfo.InvariantCulture };
      
      foreach (IFormatProvider provider in providers)
      {
         Console.WriteLine("Conversions using {0}:", ((object) provider).GetType().Name);
         foreach (string value in values)
         {
            try {
               Console.WriteLine("   Converted '{0}' to {1}.", 
                                 value, SByte.Parse(value, provider));
            }                     
            catch (FormatException) {
               Console.WriteLine("   Unable to parse '{0}'.", value);   
            }
            catch (OverflowException) {
               Console.WriteLine("   '{0}' is out of range of the SByte type.", value);         
            }
         }
      }      
   }
}
// The example displays the following output:
//       Conversions using NumberFormatInfo:
//          Unable to parse '-103'.
//          Converted '+12' to 12.
//          Converted '~16' to -16.
//          Converted '  1' to 1.
//          '~255' is out of range of the SByte type.
//       Conversions using CultureInfo:
//          Converted '-103' to -103.
//          Converted '+12' to 12.
//          Unable to parse '~16'.
//          Converted '  1' to 1.
//          Unable to parse '~255'.
open System
open System.Globalization

let nf = NumberFormatInfo()
nf.NegativeSign <- "~" 

let values = [| "-103"; "+12"; "~16"; "  1"; "~255" |]
let providers: IFormatProvider[] = [| nf; CultureInfo.InvariantCulture |]

for provider in providers do
    printfn $"Conversions using {(box provider).GetType().Name}:"
    for value in values do
        try
            printfn $"   Converted '{value}' to {SByte.Parse(value, provider)}."
        with
        | :? FormatException ->
            printfn $"   Unable to parse '{value}'."
        | :? OverflowException ->
            printfn $"   '{value}' is out of range of the SByte type."

// The example displays the following output:
//       Conversions using NumberFormatInfo:
//          Unable to parse '-103'.
//          Converted '+12' to 12.
//          Converted '~16' to -16.
//          Converted '  1' to 1.
//          '~255' is out of range of the SByte type.
//       Conversions using CultureInfo:
//          Converted '-103' to -103.
//          Converted '+12' to 12.
//          Unable to parse '~16'.
//          Converted '  1' to 1.
//          Unable to parse '~255'.
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim nf As New NumberFormatInfo()
      nf.NegativeSign = "~" 
      
      Dim values() As String = { "-103", "+12", "~16", "  1", "~255" }
      Dim providers() As IFormatProvider = { nf, CultureInfo.InvariantCulture }
      
      For Each provider As IFormatProvider In providers
         Console.WriteLine("Conversions using {0}:", CObj(provider).GetType().Name)
         For Each value As String In values
            Try
               Console.WriteLine("   Converted '{0}' to {1}.", _
                                 value, SByte.Parse(value, provider))
            Catch e As FormatException
               Console.WriteLine("   Unable to parse '{0}'.", value)   
            Catch e As OverflowException
               Console.WriteLine("   '{0}' is out of range of the SByte type.", value)         
            End Try
         Next
      Next      
   End Sub
End Module
' The example displays '
'       Conversions using NumberFormatInfo:
'          Unable to parse '-103'.
'          Converted '+12' to 12.
'          Converted '~16' to -16.
'          Converted '  1' to 1.
'          '~255' is out of range of the SByte type.
'       Conversions using CultureInfo:
'          Converted '-103' to -103.
'          Converted '+12' to 12.
'          Unable to parse '~16'.
'          Converted '  1' to 1.
'          Unable to parse '~255'.

Remarks

The s parameter contains a number of the 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 sign.
digits A sequence of digits ranging 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 with a leading sign are allowed. To explicitly define the style elements with the culture-specific formatting information that can be present in s, use the Parse(String, NumberStyles, IFormatProvider) method.

The provider parameter is an IFormatProvider implementation whose GetFormat method returns a NumberFormatInfo object that provides culture-specific information about the format of s. There are three ways to use the provider parameter to supply custom formatting information to the parse operation:

  • You can pass the actual NumberFormatInfo object that provides formatting information. (Its implementation of GetFormat simply returns itself.)

  • You can pass a CultureInfo object that specifies the culture whose formatting is to be used. Its NumberFormat property provides formatting information.

  • You can pass a custom IFormatProvider implementation. Its GetFormat method must instantiate and return the NumberFormatInfo object that provides formatting information.

If provider is null, the NumberFormatInfo object for the current culture is used.

See also

Applies to

Parse(String)

Source:
SByte.cs
Source:
SByte.cs
Source:
SByte.cs

Important

This API is not CLS-compliant.

CLS-compliant alternative
System.Int16.Parse(String)

Converts the string representation of a number to its 8-bit signed integer equivalent.

public:
 static System::SByte Parse(System::String ^ s);
[System.CLSCompliant(false)]
public static sbyte Parse (string s);
public static sbyte Parse (string s);
[<System.CLSCompliant(false)>]
static member Parse : string -> sbyte
static member Parse : string -> sbyte
Public Shared Function Parse (s As String) As SByte

Parameters

s
String

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

Returns

An 8-bit signed integer that is equivalent to the number contained in the s parameter.

Attributes

Exceptions

s is null.

s does not consist of an optional sign followed by a sequence of digits (zero through nine).

s represents a number less than SByte.MinValue or greater than SByte.MaxValue.

Examples

The following example demonstrates how to convert a string value into a signed byte value using the Parse method. The resulting signed byte value is then displayed to the console.

// Define an array of numeric strings.
string[] values = { "-16", "  -3", "+ 12", " +12 ", "  12  ",
                    "+120", "(103)", "192", "-160" };
                           
// Parse each string and display the result.
foreach (string value in values)
{
   try {
      Console.WriteLine("Converted '{0}' to the SByte value {1}.",
                        value, SByte.Parse(value));
   }
   catch (FormatException) {
      Console.WriteLine("'{0}' cannot be parsed successfully by SByte type.",
                        value);
   }                              
   catch (OverflowException) {
      Console.WriteLine("'{0}' is out of range of the SByte type.",
                        value);
   }                                                                        
}
// The example displays the following output:
//       Converted '-16' to the SByte value -16.
//       Converted '  -3' to the SByte value -3.
//       '+ 12' cannot be parsed successfully by SByte type.
//       Converted ' +12 ' to the SByte value 12.
//       Converted '  12  ' to the SByte value 12.
//       Converted '+120' to the SByte value 120.
//       '(103)' cannot be parsed successfully by SByte type.
//       '192' is out of range of the SByte type.
//       '-160' is out of range of the SByte type.
open System

// Define an array of numeric strings.
let values = 
    [| "-16"; "  -3"; "+ 12"; " +12 "; "  12  "
       "+120"; "(103)"; "192"; "-160" |]
                            
// Parse each string and display the result.
for value in values do
    try
        printfn $"Converted '{value}' to the SByte value {SByte.Parse value}."
    with
    | :? FormatException ->
        printfn $"'{value}' cannot be parsed successfully by SByte type."
    | :? OverflowException ->
        printfn $"'{value}' is out of range of the SByte type."
        
// The example displays the following output:
//       Converted '-16' to the SByte value -16.
//       Converted '  -3' to the SByte value -3.
//       '+ 12' cannot be parsed successfully by SByte type.
//       Converted ' +12 ' to the SByte value 12.
//       Converted '  12  ' to the SByte value 12.
//       Converted '+120' to the SByte value 120.
//       '(103)' cannot be parsed successfully by SByte type.
//       '192' is out of range of the SByte type.
//       '-160' is out of range of the SByte type.
' Define an array of numeric strings.
Dim values() As String = { "-16", "  -3", "+ 12", " +12 ", "  12  ", _
                           "+120", "(103)", "192", "-160" }
                           
' Parse each string and display the result.
For Each value As String In values
   Try
      Console.WriteLine("Converted '{0}' to the SByte value {1}.", _
                        value, SByte.Parse(value))
   Catch e As FormatException
      Console.WriteLine("'{0}' cannot be parsed successfully by SByte type.", _
                        value)
   Catch e As OverflowException
      Console.WriteLine("'{0}' is out of range of the SByte type.", _
                        value)
   End Try                                                                        
Next        
' The example displays the following output:
'       Converted '-16' to the SByte value -16.
'       Converted '  -3' to the SByte value -3.
'       '+ 12' cannot be parsed successfully by SByte type.
'       Converted ' +12 ' to the SByte value 12.
'       Converted '  12  ' to the SByte value 12.
'       Converted '+120' to the SByte value 120.
'       '(103)' cannot be parsed successfully by SByte type.
'       '192' is out of range of the SByte type.
'       '-160' is out of range of the SByte type.

Remarks

The s parameter contains a number of the 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 sign.
digits A sequence of digits ranging from 0 to 9.

The s parameter is interpreted using the NumberStyles.Integer style. In addition to the byte value's decimal digits, only leading and trailing spaces with a leading positive or negative sign are allowed. To explicitly define the style elements that can be present in s, use either the Parse(String, NumberStyles) or the Parse(String, NumberStyles, IFormatProvider) method.

The s parameter is parsed by using the formatting information in a NumberFormatInfo that is initialized for the current system culture. For more information, see NumberFormatInfo.CurrentInfo. To parse a string by using the formatting information of some other culture, use the Parse(String, NumberStyles, IFormatProvider) method.

See also

Applies to

Parse(ReadOnlySpan<Char>, IFormatProvider)

Source:
SByte.cs
Source:
SByte.cs
Source:
SByte.cs

Parses a span of characters into a value.

public:
 static System::SByte Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<System::SByte>::Parse;
public static sbyte Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> sbyte
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As SByte

Parameters

s
ReadOnlySpan<Char>

The span of characters to parse.

provider
IFormatProvider

An object that provides culture-specific formatting information about s.

Returns

The result of parsing s.

Implements

Applies to

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Source:
SByte.cs
Source:
SByte.cs

Parses a span of UTF-8 characters into a value.

public:
 static System::SByte Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<System::SByte>::Parse;
public static sbyte Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> sbyte
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As SByte

Parameters

utf8Text
ReadOnlySpan<Byte>

The span of UTF-8 characters to parse.

provider
IFormatProvider

An object that provides culture-specific formatting information about utf8Text.

Returns

The result of parsing utf8Text.

Implements

Applies to

Parse(String, NumberStyles)

Source:
SByte.cs
Source:
SByte.cs
Source:
SByte.cs

Important

This API is not CLS-compliant.

CLS-compliant alternative
System.Int16.Parse(String)

Converts the string representation of a number in a specified style to its 8-bit signed integer equivalent.

public:
 static System::SByte Parse(System::String ^ s, System::Globalization::NumberStyles style);
[System.CLSCompliant(false)]
public static sbyte Parse (string s, System.Globalization.NumberStyles style);
public static sbyte Parse (string s, System.Globalization.NumberStyles style);
[<System.CLSCompliant(false)>]
static member Parse : string * System.Globalization.NumberStyles -> sbyte
static member Parse : string * System.Globalization.NumberStyles -> sbyte
Public Shared Function Parse (s As String, style As NumberStyles) As SByte

Parameters

s
String

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

style
NumberStyles

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

Returns

An 8-bit signed integer that is equivalent to the number specified in s.

Attributes

Exceptions

s is not in a format that is compliant with style.

s represents a number less than SByte.MinValue or greater than SByte.MaxValue.

-or-

s includes non-zero, fractional digits.

style is not a NumberStyles value.

-or-

style is not a combination of AllowHexSpecifier and HexNumber values.

Examples

The following example parses string representations of SByte values with the Parse(String, NumberStyles) method. The current culture for the example is en-US.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      NumberStyles style;
      sbyte number;

      // Parse value with no styles allowed.
      string[] values1 = { " 121 ", "121", "-121" };
      style = NumberStyles.None;
      Console.WriteLine("Styles: {0}", style.ToString());
      foreach (string value in values1)
      {
         try {
            number = SByte.Parse(value, style);
            Console.WriteLine("   Converted '{0}' to {1}.", value, number);
         }   
         catch (FormatException) {
            Console.WriteLine("   Unable to parse '{0}'.", value);
         }
      }
      Console.WriteLine();
            
      // Parse value with trailing sign.
      style = NumberStyles.Integer | NumberStyles.AllowTrailingSign;
      string[] values2 = { " 103+", " 103 +", "+103", "(103)", "   +103  " };
      Console.WriteLine("Styles: {0}", style.ToString());
      foreach (string value in values2)
      {
         try {
            number = SByte.Parse(value, style);
            Console.WriteLine("   Converted '{0}' to {1}.", value, number);
         }   
         catch (FormatException) {
            Console.WriteLine("   Unable to parse '{0}'.", value);
         }      
         catch (OverflowException) {
            Console.WriteLine("   '{0}' is out of range of the SByte type.", value);         
         }
      }      
      Console.WriteLine();
   }
}
// The example displays the following output:
//       Styles: None
//          Unable to parse ' 121 '.
//          Converted '121' to 121.
//          Unable to parse '-121'.
//       
//       Styles: Integer, AllowTrailingSign
//          Converted ' 103+' to 103.
//          Converted ' 103 +' to 103.
//          Converted '+103' to 103.
//          Unable to parse '(103)'.
//          Converted '   +103  ' to 103.
open System
open System.Globalization

// Parse value with no styles allowed.
let values1 = [| " 121 "; "121"; "-121" |]
let style = NumberStyles.None
printfn $"Styles: {style}"
for value in values1 do
    try
        let number = SByte.Parse(value, style)
        printfn $"   Converted '{value}' to {number}."
    with :? FormatException ->
        printfn $"   Unable to parse '{value}'."
printfn ""
            
// Parse value with trailing sign.
let style2 = NumberStyles.Integer ||| NumberStyles.AllowTrailingSign
let values2 = [| " 103+"; " 103 +"; "+103"; "(103)"; "   +103  " |]
printfn $"Styles: {style2}"
for value in values2 do
    try
        let number = SByte.Parse(value, style2)
        printfn $"   Converted '{value}' to {number}."
    with 
    | :? FormatException ->
        printfn $"   Unable to parse '{value}'."
    | :? OverflowException ->
        printfn $"   '{value}' is out of range of the SByte type."         
printfn ""
// The example displays the following output:
//       Styles: None
//          Unable to parse ' 121 '.
//          Converted '121' to 121.
//          Unable to parse '-121'.
//       
//       Styles: Integer, AllowTrailingSign
//          Converted ' 103+' to 103.
//          Converted ' 103 +' to 103.
//          Converted '+103' to 103.
//          Unable to parse '(103)'.
//          Converted '   +103  ' to 103.
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim style As NumberStyles
      Dim number As SByte

      ' Parse value with no styles allowed.
      Dim values1() As String = { " 121 ", "121", "-121" }
      style = NumberStyles.None
      Console.WriteLine("Styles: {0}", style.ToString())
      For Each value As String In values1
         Try
            number = SByte.Parse(value, style)
            Console.WriteLine("   Converted '{0}' to {1}.", value, number)
         Catch e As FormatException
            Console.WriteLine("   Unable to parse '{0}'.", value)   
         End Try
      Next
      Console.WriteLine()
            
      ' Parse value with trailing sign.
      style = NumberStyles.Integer Or NumberStyles.AllowTrailingSign
      Dim values2() As String = { " 103+", " 103 +", "+103", "(103)", "   +103  " }
      Console.WriteLine("Styles: {0}", style.ToString())
      For Each value As String In values2
         Try
            number = SByte.Parse(value, style)
            Console.WriteLine("   Converted '{0}' to {1}.", value, number)
         Catch e As FormatException
            Console.WriteLine("   Unable to parse '{0}'.", value)   
         Catch e As OverflowException
            Console.WriteLine("   '{0}' is out of range of the SByte type.", value)         
         End Try
      Next      
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'       Styles: None
'          Unable to parse ' 121 '.
'          Converted '121' to 121.
'          Unable to parse '-121'.
'       
'       Styles: Integer, AllowTrailingSign
'          Converted ' 103+' to 103.
'          Converted ' 103 +' to 103.
'          Converted '+103' to 103.
'          Unable to parse '(103)'.
'          Converted '   +103  ' to 103.

Remarks

The style parameter defines the style elements (such as white space or the positive or negative sign symbol) 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]exponential_digits][ws]

If style includes NumberStyles.AllowHexSpecifier, the s parameter may contain the following elements:

[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, and it can appear 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 current culture. The current culture's currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
sign An optional sign. The sign can appear at the beginning of s if style includes the NumberStyles.AllowLeadingSign flag, and it can appear at the end of s if style includes the NumberStyles.AllowTrailingSign flag. Parentheses can be used in s to indicate a negative value if style includes the NumberStyles.AllowParentheses flag.
digits A sequence of digits from 0 through 9.
. A culture-specific decimal point symbol. The current culture's decimal point symbol can appear in s if style includes the NumberStyles.AllowDecimalPoint flag.
fractional_digits One or more occurrences of the digit 0-9 if style includes the NumberStyles.AllowExponent flag, or one or more occurrences of the digit 0 if it does not. 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 (scientific) notation. The s parameter can represent a number in exponential notation if style includes the NumberStyles.AllowExponent flag.
exponential_digits One or more occurrences of the digit 0-9. 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.

Note

Any terminating NUL (U+0000) characters in s are ignored by the parsing operation, regardless of the value of the style argument.

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 present, but are not required to be present, in the 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 decimal point (.) and fractional_digits elements. However, if style does not include the NumberStyles.AllowExponent flag, fractional_digits must consist of only one or more 0 digits; otherwise, an OverflowException is thrown.
NumberStyles.AllowExponent The "e" or "E" character, which indicates exponential notation, along with exponential_digits.
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 before digits.
NumberStyles.AllowTrailingSign A positive sign after digits.
NumberStyles.AllowParentheses The sign element in the form of parentheses enclosing the numeric value.
NumberStyles.AllowThousands The group separator (,) element. Although the group separator can appear in s, it must be preceded by only one or more 0 digits.
NumberStyles.AllowCurrencySymbol The currency ($) element.

If the NumberStyles.AllowHexSpecifier flag is used, s must be a hexadecimal value. Valid hexadecimal digits are 0-9, a-f, and A-F. A prefix such as "0x" is not supported and causes the parse operation to fail. The only other flags that can be combined included in style are NumberStyles.AllowLeadingWhite and NumberStyles.AllowTrailingWhite. (The NumberStyles enumeration includes a composite number style, NumberStyles.HexNumber, that includes both white-space flags.)

Note

If the s parameter is the string representation of a hexadecimal number, it cannot be preceded by any decoration (such as 0x or &h) that differentiates it as a hexadecimal number. This causes the parse operation to throw an exception.

If s represents a hexadecimal number, the Parse(String, NumberStyles) method interprets the high-order bit of the byte as a sign bit.

The s parameter is parsed by using the formatting information in a NumberFormatInfo object that is initialized for the current system culture. To use the formatting information of some other culture, call the Parse(String, NumberStyles, IFormatProvider) overload.

See also

Applies to