C# Byte TryParse(String, Byte)

Description

Byte 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.

Syntax

Byte.TryParse(String, Byte) has the following syntax.


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

Parameters

Byte.TryParse(String, Byte) has the following parameters.

  • s - A string that contains a number to convert. The string is interpreted using the Integer style.
  • result - 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.

Returns

Byte.TryParse(String, Byte) method returns true if s was converted successfully; otherwise, false.

Example

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


//w ww  .ja v  a2  s  . c  o  m
using System;

public class MainClass 
{
   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 code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version