5

I am coding a text based adventure, and am having a problem. I am trying to make a switch statement case that handles every examination action you want, and am getting this for my code so far:

case "examine" + string x:
    //this is a method that I made that makes sure that it is an object in the area
    bool iseobj = tut.Check(x);
    if (iseobj)
        x.examine();
    else
        Console.WriteLine("That isn't an object to examine");
    break;

How do I use a variable in my case statement? I want any string starting with "examine" + (x) to trigger the case.

3
  • 1
    You mean you want this as an variable Console.WriteLine("That isn't an object to examine"); ? Commented Jul 8, 2016 at 5:18
  • 3
    cases in switch statement must be constant. it cannot contain variables Commented Jul 8, 2016 at 5:24
  • I edited your question to be more clear, let me know if I understood it correctly :) Commented Jul 8, 2016 at 6:02

1 Answer 1

6

Your scenario would fit into an if-else statement better than a switch statement. In C#, a switch can only evaluate values, not expressions. This means you can't do:

case input.StartsWith("examine"):

However, you can make this work with an if statement! Consider doing the following:

if (input.StartsWith("examine"))
{
    //this is a method that I made that makes sure that it is an object in the area
    bool iseobj = tut.Check(x);
    if (iseobj)
        x.examine();
    else
        Console.WriteLine("That isn't an object to examine");
}
else if (...) // other branches here
Sign up to request clarification or add additional context in comments.

6 Comments

Should case StartsWith( read case input.StartsWith( ? Otherwise jolly good answer
@MickyD Thanks for the catch!
@Fireball175 If you want to get your x variable you could do string x = s.Split(new[] { "examine" }, StringSplitOptions.RemoveEmptyEntries)[0] inside the if.
@ArthurRey it says string doesn't contain a defenition for 'examine', any ideas?
@ArthurRey figuring out how to fix it, but thankyou so much for the help, I really appreciate it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.