Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Implicit conversion from 8-bit signed integer (SByte) to Decimal in C#
SByte represents an 8-bit signed integer with values ranging from -128 to 127. C# allows implicit conversion from sbyte to decimal because this conversion is always safe and does not result in data loss.
Syntax
Following is the syntax for implicit conversion from sbyte to decimal −
sbyte sbyteValue = value; decimal decimalValue = sbyteValue; // implicit conversion
How It Works
The conversion happens automatically without requiring explicit casting because decimal can represent all possible sbyte values without precision loss. The 8-bit signed integer is widened to fit into the 128-bit decimal format.
Example
The following example demonstrates implicit conversion from sbyte to decimal −
using System;
public class Demo {
public static void Main() {
sbyte val = 39;
decimal d;
Console.WriteLine("Implicit conversion from 8-bit signed integer (sbyte) to Decimal");
d = val; // implicit conversion happens here
Console.WriteLine("SByte value: " + val);
Console.WriteLine("Decimal value: " + d);
Console.WriteLine("Type of d: " + d.GetType());
}
}
The output of the above code is −
Implicit conversion from 8-bit signed integer (sbyte) to Decimal SByte value: 39 Decimal value: 39 Type of d: System.Decimal
Using Negative Values
The conversion also works seamlessly with negative sbyte values −
using System;
public class Demo {
public static void Main() {
sbyte negativeVal = -75;
sbyte maxVal = 127;
sbyte minVal = -128;
decimal d1 = negativeVal;
decimal d2 = maxVal;
decimal d3 = minVal;
Console.WriteLine("Negative SByte (-75) to Decimal: " + d1);
Console.WriteLine("Maximum SByte (127) to Decimal: " + d2);
Console.WriteLine("Minimum SByte (-128) to Decimal: " + d3);
}
}
The output of the above code is −
Negative SByte (-75) to Decimal: -75 Maximum SByte (127) to Decimal: 127 Minimum SByte (-128) to Decimal: -128
Direct Assignment Example
You can also perform the conversion during variable declaration −
using System;
public class Demo {
public static void Main() {
sbyte val = 51;
decimal d = val; // implicit conversion during declaration
Console.WriteLine("Original SByte: " + val);
Console.WriteLine("Converted Decimal: " + d);
// Verify decimal precision is maintained
Console.WriteLine("Decimal with precision: " + d.ToString("F2"));
}
}
The output of the above code is −
Original SByte: 51 Converted Decimal: 51 Decimal with precision: 51.00
Conclusion
Implicit conversion from sbyte to decimal in C# is automatic and safe, requiring no explicit casting. This conversion preserves all values in the sbyte range (-128 to 127) without data loss, making it a reliable widening conversion.
