convert.ToSByte(string, IFormatProvider) Method in C#
In this article, we will discuss the convert.ToSbyte() method in C# with its syntax, parameters, exceptions, and examples.
What is the convert.ToSbyte() method?
The convert.ToSbyte() method transforms the given string representation of a number into an equivalent 8-bit signed integer using the specified culture-specific formatting information.
Syntax:
It has the following syntax:
public static sbyte ToSByte (string value, IFormatProvider provider);
Parameters:
- value: The number to be converted is contained in a string.
- provider: It is a commodity that offers formatting details specific to a certain culture.
- Return Value: The value returned by this method is an 8-bit signed integer.
Exceptions:
- ArgumentNullException: If the value is null, raise ArgumentNullException.
- FormatException: When a value is entered without an optional sign and then a string of digits (0 through 9).
- OverFlowException: If the value is either greater than or less than the maximum value.
Example:
Let us take an example to illustrate the Convert.ToSbyte() method in C#.
using System;
using System.Globalization;
class CustomFormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
{
return this;
}
else
{
return null;
}
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg is sbyte)
{
// Custom formatting logic for sbyte
sbyte value = (sbyte)arg;
return $"Formatted SByte: {value.ToString(format, CultureInfo.InvariantCulture)}";
}
else
{
// Use default formatting for other types
return arg.ToString();
}
}
}
class Program
{
static void Main()
{
string numberString = "42";
try
{
// Using Convert.ToSByte with a custom format provider
sbyte result = Convert.ToSByte(numberString, new CustomFormatProvider());
Console.WriteLine($"Converted and formatted value: {result}");
}
catch (FormatException)
{
Console.WriteLine("Invalid format for conversion.");
}
catch (OverflowException)
{
Console.WriteLine("Value is outside the range of a signed byte.");
}
}
}
Output:
Converted and formatted value: 42
If the string number is example 425
Value is outside the range of a signed byte.
Explanation:
- In this example, we use the IFormatProvider and ICustomFormatter interfaces implemented by the custom format provider (CustomFormatProvider). For the sbyte type, the CustomFormatProvider offers unique formatting logic.
- An instance of CustomFormatProvider is passed as the second argument when calling Convert.ToSByte. By using the custom logic specified in the format provider, we can now regulate how the converted sbyte value is formatted.
- It allows modifying the input numbering and the CustomFormatProvider class to meet unique needs.
Example 2:
Let us take another example to illustrate the Convert.ToSbyte() method in C#.
using System;
using System.Globalization;
class Program
{
// Main Method
public static void Main()
{
try
{
// Creating an object of CultureInfo
CultureInfo customCulture = new CultureInfo("en-US");
// Declaring and initializing an array of string values
string[] numericStrings = { "42", "+99", "-75" };
// Calling the ConvertAndDisplaySByteValues() method
Console.Write("Converted sbyte values from specified strings: ");
ConvertAndDisplaySByteValues(numericStrings, customCulture);
}
catch (FormatException e)
{
Console.WriteLine("\n");
Console.Write("FormatException Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
catch (OverflowException e)
{
Console.WriteLine("\n");
Console.Write("OverflowException Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
// Defining the ConvertAndDisplaySByteValues() method
public static void ConvertAndDisplaySByteValues(string[] values, CultureInfo culture)
{
foreach (var stringValue in values)
{
// Converting string to specified sbyte using the specified culture
sbyte convertedValue = Convert.ToSByte(stringValue, culture);
// Displaying the converted sbyte value
Console.Write(" {0}, ", convertedValue);
}
}
}
Output:
Converted sbyte values from specified strings: 42, 99, -75.
Example 3:
Let us take another example to illustrate the Convert.ToSbyte() method in C#.
using System;
using System.Globalization;
class Program
{
// Main Method
public static void Main()
{
try
{
// Creating an object of CultureInfo
CultureInfo customCulture = new CultureInfo("en-US");
// Declaring and initializing an array of string values
string[] numericStrings = { "55", "+28", "-93" };
// Calling the ConvertAndDisplaySByteValues() method
Console.Write("Converted sbyte values of specified strings: ");
ConvertAndDisplaySByteValues(numericStrings, customCulture);
Console.WriteLine("\n");
// Example demonstrating MinValue and OverflowException
string s = "9007199254740992"; // A value larger than SByte.MaxValue
Console.WriteLine("s is greater than the MaxValue");
// Converting string to specified sbyte
sbyte val = Convert.ToSByte(s, customCulture);
// Displaying the converted sbyte value
Console.Write(" {0}, ", val);
}
catch (FormatException e)
{
Console.Write("FormatException Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
catch (OverflowException e)
{
Console.Write("OverflowException Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
// Defining the ConvertAndDisplaySByteValues() method
public static void ConvertAndDisplaySByteValues(string[] values, CultureInfo culture)
{
foreach (var stringValue in values)
{
// Converting string to specified sbyte using the specified culture
sbyte convertedValue = Convert.ToSByte(stringValue, culture);
// Displaying the converted sbyte value
Console.Write(" {0}, ", convertedValue);
}
}
}
OUTPUT:
Converted sbyte values of specified strings: 55, 28, -93,
s is greater than the MaxValue
OverflowException Thrown: System.OverflowException
Conclusion:
In conclusion, the provided C# program shows how to convert string representations of numbers into signed bytes (sbyte) using the Convert.ToSByte() method. The program uses a custom CultureInfo object to specify formatting rules during the conversion process. It demonstrates how to successfully use a custom culture to convert various numeric strings, including those with positive, negative, and zero values. The program also contains an example that shows how the method handles values larger than SByte.MaxValue, which causes an OverflowException to occur. It illustrates how crucial it is to validate input values to make sure they are within a signed byte's valid range. Through the use of try-catch blocks to catch potential FormatExceptions and OverflowExceptions that may arise during the conversion process, the code structure places a strong emphasis on error handling.