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 Char to Decimal in C#
In C#, implicit conversion from char to decimal happens automatically when you assign a character value to a decimal variable. The character is converted to its corresponding ASCII or Unicode numeric value, which is then stored as a decimal number.
Syntax
Following is the syntax for implicit conversion from char to decimal −
char c = 'character'; decimal dec = c; // implicit conversion
How It Works
When you assign a char to a decimal, C# automatically converts the character to its numeric ASCII/Unicode value. For example, the character 'A' has an ASCII value of 65, so it becomes 65.0 when converted to decimal.
Example
using System;
public class Demo {
public static void Main() {
char c = 'p';
decimal dec;
Console.WriteLine("Implicit conversion from Char to Decimal");
dec = c;
Console.WriteLine("Character: " + c);
Console.WriteLine("Decimal value: " + dec);
}
}
The output of the above code is −
Implicit conversion from Char to Decimal Character: p Decimal value: 112
Multiple Character Conversions
Example
using System;
public class CharToDecimalDemo {
public static void Main() {
char[] characters = {'A', 'B', 'Z', 'a', 'z', '0', '9'};
Console.WriteLine("Character to Decimal Conversions:");
Console.WriteLine("----------------------------------");
foreach (char ch in characters) {
decimal decValue = ch; // implicit conversion
Console.WriteLine($"'{ch}' -> {decValue}");
}
}
}
The output of the above code is −
Character to Decimal Conversions: ---------------------------------- 'A' -> 65 'B' -> 66 'Z' -> 90 'a' -> 97 'z' -> 122 '0' -> 48 '9' -> 57
Common ASCII Values
| Character | ASCII Value | Decimal Result |
|---|---|---|
| 'A' to 'Z' | 65 to 90 | 65.0 to 90.0 |
| 'a' to 'z' | 97 to 122 | 97.0 to 122.0 |
| '0' to '9' | 48 to 57 | 48.0 to 57.0 |
Conclusion
Implicit conversion from char to decimal in C# automatically converts characters to their ASCII/Unicode numeric values. This conversion is useful when you need to perform mathematical operations on character data or when working with character codes in decimal format.
