Fraser Jones
Fraser Jones

Reputation: 1

How would I convert a var into a string?

string decisionPath1;

var _Key = Console.ReadKey(true); 

decisionPath1 = (string)_Key.Key;

while (_Key.Key == ConsoleKey.R) 
 ... //Do something

This is for a school project and I would be grateful for any help.

Upvotes: 0

Views: 411

Answers (2)

cancmrt
cancmrt

Reputation: 139

You need KeyChar property for this after that you can convert char to string. Key part is in code:

string desionPath1 = _Key.KeyChar.ToString();

You can look code in here

using System;

public class Program
{
    public static void Main()
    {
         var _Key = Console.ReadKey(true); 

         string desionPath1 = _Key.KeyChar.ToString();

        Console.WriteLine(desionPath1);
    }
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503579

var is just a way of implicitly declaring the type of the variable. Console.ReadKey() is declared to return ConsoleKeyInfo, so your declaration is exactly equivalent to:

ConsoleKeyInfo _Key = Console.ReadKey(true);

To find the string representation for desionPath1, you could use _Key.KeyChar.ToString() potentially. You should look at the documentation for ConsoleKeyInfo to see what's available.

Alternatively, if you're just wanting to read text from the console, you might want to use Console.ReadLine() or similar instead of Console.ReadKey.

Upvotes: 7

Related Questions