Convert.Tosbyte(String, Iformatprovider) Method In C#

In this article, you will learn about the Convert.ToSByte(String, IFormatProvider) method in C# with its syntax, parameters, and examples.

What is Convert.ToSByte(String, IFormatProvider) method?

In C#, the Convert.ToSByte(String, IFormatProvider) method converts the specified string representation of a number to an equivalent signed byte (SByte) , using the specified format provider.

Syntax:

It has the following syntax:

Example

public static sbyte ToSByte(string value, IFormatProvider provider);

Parameters:

value: A string containing the number to convert.

provider: It is an IFormatProvider that supplies culture-specific formatting information. It can be null to use the default format provider.

Return Value:

As a result of the conversion, the process returns a signed byte (sbyte).

Exceptions:

It is important to handle exceptions suitably thrown by the procedure. Examples of frequent exceptions are:

  • FormatException: It is thrown when a string's format is incorrect, known as a FormatException.
  • OverflowException: An overflow exception is raised if the conversion causes an overflow.
  • Example:

Let us take an example to illustrate the Convert.ToSByte(String, IFormatProvider) method in C#.

Example

using System;
using System.Globalization;
class Demo
{
    static void Main()
    {
        // Example 1: Valid conversion
        PerformingSByteConversion("123");
        // Example 2: Invalid format
        PerformingSByteConversion("abc");
        // Example 3: Overflow occurred
        PerformingSByteConversion("256");
        // Example 4: Using a custom format provider
        IFormatProvider customFormatProvider = new CultureInfo("fr-FR"); // French culture
        PerformingSByteConversion("123,45", customFormatProvider);
    }
    static void PerformingSByteConversion(string value, IFormatProvider provider = null)
    {
        Console.WriteLine($"Attempting to convert '{value}' to SByte.");
        try
        {
            sbyte result_value = Convert.ToSByte(value, provider);
            Console.WriteLine($"Conversion successful, and the Result is {result_value}");
        }
        catch (FormatException)
        {
            Console.WriteLine("Invalid format for the conversion.");
        }
        catch (OverflowException)
        {
            Console.WriteLine("The overflow occurred during the conversion.");
        }
        catch (Exception e)
        {
            Console.WriteLine($"An unexpected exception occurred: {e.Message}");
        }
        Console.WriteLine();
    }
}

Output:

Output

Attempting to convert '123' to SByte.
Conversion successful, and the Result is 123
Attempting to convert 'abc' to SByte.
Invalid format for the conversion.
Attempting to convert '256' to SByte.
The overflow occurred during the conversion.
Attempting to convert '123,45' to SByte.
Invalid format for the conversion.

Explanation:

  1. Main Method: The Main method is the entry point of the program. It demonstrates four different ways to use the PerformingSByteConversion method to convert strings to sbyte.

Example 1: A valid conversion using the string "123" .

Example 2: An invalid format conversion attempt made on the string "abc".

Example 3: An attempt to convert the string "256" results in an overflow.

Example 4: Converting the string "123,45" with a custom format provider (fr-FR - French culture).

  1. Performing the SbyteConversion Method: This method is responsible for carrying out the ToSByte functionality and handling possible exceptions.
  • The method accepts a value and an optional provider parameter for a custom format provider.
  • It prints a message indicating the attempt to convert the provided string.
  • It attempts to convert the string into a sbyte i nside the try block.
  • It prints the Result if the conversion is successful.
  • If a FormatException occurs, it handles it by printing a message about an invalid format.
  • If an OverflowException occurs, it handles it by printing a message about an overflow.
  • The catch (Exception e) block is a generic catch-all for any unexpected exceptions, printing a message with the exception details.
  • Each situation concludes with an empty line for better readability in the console output.
  • Format Exception:

Let us take an example to illustrate the format exception in Convert.ToSByte(String, IFormatProvider) method in C#.

Example

using System;
using System.Globalization;
class Demo
{
    static void Main()
    {
        string String_Value = "pqr";
        IFormatProvider customFormatProvider = new CultureInfo("en-US"); 
        try
        {
            sbyte result_value = Convert.ToSByte(String_Value, customFormatProvider);
            Console.WriteLine($"Converted value: {result_value}");
        }
        catch (FormatException e)
        {
            Console.WriteLine($"Format exception: {e.Message}");
        }
    }
}

Output:

Output

Format exception: The input string was not in the correct format.

Explanation:

This code demonstrates using "Convert.ToSByte" with a custom format provider and handling a FormatException if the conversion cannot be performed successfully. As it cannot be transformed into a signed byte in this particular case, the non-numeric string "pqr" raises a FormatException. After that, the exception message is printed to the console.

Overflow Exception:

Let us take an example to illustrate the overflow exception in Convert.ToSByte(String, IFormatProvider) method in C#.

Example

using System;
using System.Globalization;
class Demo
{
    static void Main()
    {
        string string_value = "128";
        try
        {
            sbyte result_value = Convert.ToSByte(string_value,CultureInfo.InvariantCulture);
            Console.WriteLine("Conversion successful: " + result_value);
        }
        catch (OverflowException e)
        {
            Console.WriteLine("Overflow Exception: " + e.Message);
        }
        catch (FormatException e)
        {
            Console.WriteLine("Format Exception: " + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("An unexpected error occurred: " + e.Message);
        }
    }
}

Output:

Output

Overflow Exception: The value was too large or too small for a signed byte.

Explanation:

In this example, "Convert.ToSByte" is used to attempt to convert the string "128" to a signed byte; however, the Result is beyond the allowed range for a signed byte (-128 to 127). As a result, an OverflowException will be raised, and the code will catch and handle the exception accordingly.

Input Required

This code uses input(). Please provide values below: