Question

I'm creating an OS in cosmos ( C# ) , but I cannot get the code right. Here it is:

var input = Console.ReadLine();
if (input = 'h')
    Console.Write("This is the help section...");
else
    Console.Write("Invalid Command.");
Console.WriteLine(input);

What I want it to do is that when I type in 'H' it should output the help section and when I type in something else, it should type in 'Invalid Command'.

It keeps saying 'Error: Cannot implicitly convert type 'char' to 'string'.

Full code

using System;
using System.Collections.Generic;
using System.Text;
using Sys = Cosmos.System;

namespace Dingo_OS
{
    public class Kernel : Sys.Kernel
    {
        protected override void BeforeRun()
        {
        Console.WriteLine("Thank you for trying out my OS. For any help, input /h.");
        }

        protected override void Run()
        {
            var input = Console.ReadLine();
            if (input = 'h')
                Console.Write("This is the help section...");
            else
                Console.Write("Invalid Command.");
            Console.WriteLine(input);
        }
    }
}
Was it helpful?

Solution

Console.ReadLine returns a string, not a single character. So you need to compare it with a string. String literals uses double quotes, not single quotes. Also, you want the equality comparison operator (==) rather than the assignment operator (=):

if (input == "h")

To be honest, if you're sufficiently inexperienced in C# that this is causing you problems, I suggest you take a step back and learn the basics of C# in a more "normal" environment (e.g. console or client apps) first, before venturing into Cosmos. I haven't done any Cosmos work myself, but I suspect there will be some pretty tricky areas, which will be made much harder by not having a solid grounding in C# first.

OTHER TIPS

Console.ReadLine returns a string not a char, you can use Console.ReadKey().KeyChar for reading char

protected override void Run()
{
    var input = Console.ReadKey().KeyChar;
    if (input == 'h')
        Console.Write("This is the help section...");
    else
        Console.Write("Invalid Command.");
    Console.WriteLine(input);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top