Reputation: 43
I'm currently learning C#.
a little bit confused about convertion
especially converting character to string;
The code isn't working.
this line : Console.WriteLine(Char.ToString(i));
is converting a character to string possible? i just used character because its a letter choices. if i use a string it will be easy for me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SwitchStatement.Example
{
class SwitchSt
{
static void Main()
{
char i;
Console.WriteLine("Who is the current President of the United States?");
Console.WriteLine("\nA.) Barack Obama\n"
+ "B.) George Bush\n"
+ "C.) Bill Gates\n"
);
Console.Write("Type the letter of your answer : ");
Console.ReadLine(Char.ToString(i));
switch(i)
{
case 'a' :
break;
}
Console.ReadKey();
}
}
}
Upvotes: 1
Views: 149
Reputation: 107407
The problem is that you'll need to assign or prompt the user for the char before displaying it. You'll receive the error:
Use of unassigned local variable 'i'
In addition to static Char.ToString(ch)
, it is more common to convert a char to a String, using the variable instance i
.
Console.WriteLine(i.ToString());
However, there is also an overload of WriteLine
which takes a char directly:
Console.WriteLine(i);
Which IMO would be preferable as it has the least ceremony
surrounding the char.
Edit
Use one of the Console.Read*
methods to read the char. Here's Console.Read
. Note that as Read
returns an int, you'll need to cast to a char
.
Console.Write("Type the letter of your answer : ");
char i = (char)Console.Read();
Console.WriteLine(i);
Final point - many will find the use of i
for a char surprising, as i,j + k
are typically used for integers, especially counters. Possibly rename char i
to char ch
or similar?
Upvotes: 0
Reputation: 1620
you can simply use a pre-defined method ToString()
for this , like this example below ;
char ch = 'a';
Console.WriteLine(ch.ToString()); // Output: "a"
To read input char
Console.Write("Enter a alphabet: ");
char a = (char)Console.Read();
Console.Write("Enter your age: ");
age = Convert.ToInt32(Console.ReadLine());
//Show the details you typed
Console.WriteLine("your letter is {0}.", a.ToString());
Console.WriteLine("Age is {0}.", age);
Upvotes: 2