EDIT: For a console application, not sure if someone can add that to the end of the title?

I could only think of it as a function, as I'm not too heavily into C# just yet.

What I'm doing is creating a MUD-style game as a console application, so players will read text describing a room, and will use numbers or y/n to select an option, and a response will generate depending on their input. As such, my code will be growing quite long, as I was wondering if there was a way to make it so if one section is complete and I want to repeat their choices, rather than make an if statement for the condition and re-paste the lines, if I could assign a value to a variable at the end of a section, and use System.Console.Readline(variable) to repeat what is within. Like a loop for when an input equals a certain value, but no looping, just stored so it's on call if I want to bring it up again. So people can make a choice, and re-make the choice if they wish.

I don't think I worded that very well, so I'll post some code as to what I'm wanting (I won't do datatype conversions to keep it minimalistic here).

int userInput;
bool opt1 = false;

//(Section 1 - These three lines are what I want repeated if they input '2')
System.Console.WriteLine("What would you like to do?");
System.Console.WriteLine("\n\n 1) Buy\n2) Repeat questionl\n");
userInput = System.Console.ReadLine();

if (userInput = 1) {
System.Console.WriteLine("What do you want to buy?");
System.Console.WriteLine("More things here...");
System.Console.Readline();
opt1 = true;
}

if(userInput = 2) {
//(Some line of code that repeats first three lines if opt = true)
}

Something like that, but I'd like, if possible, to write something that can call a number. So I can have section 1 within curly brackets with content inside, and then if I want that repeated later I could say System.Console.WriteLine(somefunction(1)); and have it repeat what is within the brackets for 1.

I can clarify if my post isn't easy to understand. Any help you can provide is appreciated, :).

Use something like this:

while (true)
{
    //do your thing
}

Use a continue; statement to stay in the infinite loop or leave it with a break; statement.

Use something like this:

while (true)
{
    //do your thing
}

Use a continue; statement to stay in the infinite loop or leave it with a break; statement.

So I imagine that if I use my example code, I can do the following?

int userInput;
bool opt1 = false;
 
while (userInput = 2 || userInput = "") continue; {
System.Console.WriteLine("What would you like to do?");
System.Console.WriteLine("\n\n 1) Buy\n2) Repeat question\n");
userInput = System.Console.ReadLine();
}

if (userInput = 1) {
System.Console.WriteLine("What do you want to buy?");
System.Console.WriteLine("More things here...");
System.Console.Readline();
break;
}
 
if(userInput = 2) {
opt1=false;
}

Will that then, after the user hits 'Enter' to submit their value of '2', repeat what is in the while loop? I tried to alter my code above and I'm not sure if it's 100% correct.

As you can tell, I'm not the most adept at programming. Sorry if this is all very simple to answer. I'll be trying your solution tomorrow as it's quite late here, I'm trying to brainstorm this without turning my laptop on, ha ha.

No, more something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int userInput;
            while (true)
            {
                System.Console.WriteLine("What would you like to do?");
                System.Console.WriteLine("\n\n1) Buy\n2) Repeat question\n");
                bool b = int.TryParse(Console.ReadLine(),out userInput);
                // do a check on your userinput here
                // also remember that Console.ReadLine always returns a string
                if (userInput == 1)
                {
                    // stuff here
                    break;
                }
                else if (userInput == 2)
                {
                    // stuff here
                    continue;
                }
            }
            //Console.ReadKey();
        }
    }
}
commented: Educated me on something in C# my book hadn't covered, or I didn't find. Very helpful responses. +0

Thanks, this is great. Is there perhaps a way to bundle the functionality into some form of function, or callable element? My original idea was to have the same functionality as this, but able to be called via a single line at different points. So if I wanted to have two merchants selling the same items, I could have them in some form of identifiable loop, that could be called later. Is that possible? For example, having Loop1, and when I want it later doing something like System.Console.WriteLine(Loop1);?

Thanks for all the help this far in.

I think what you need is a static method within Program to write out some text on demand.

class Program
    {
        static void Main(string[] args)
        {
            Display(); //display your outside message
            Store();   //display your store's wares
            LeaveStore(); //up to you to implement
            Display(); //display outside message again
        }

        public static void Display()
        {
            Console.WriteLine("It was a dark and stormy night");
        }

        public static void Store()
        {
            Console.WriteLine("In this store you can buy a cola, french fries, or a sandwich");

        }
    }

Mind you it's not an ideal solution but it would tide you over until you learned more about classes.

Thanks, I'll try that this evening. From what I see in your solution, would I be able to have public static void Display(1), and call Display(1)? I'll be trying something similar to that this evening, but I thought I'd ask in the meantime. I'll research a bit more about classes as well, rather than continuing to go ahead as I have been, :).

Display(1) wouldn't work unless your method has a parameter. You could make a bunch of methods called Display1 thru whatever, but that may not be the most effective approach. There are a number of options open to you with string arrays too (so making an array and knowing which elements to pick and combine, etc.).
Definitely look up classes. I've seen people working on RPG type games that expend a ton of effort on sections of it that they could have easily done in minutes with a loop structure or the like. So needing to organize your code into "functions" is at least a step in the right direction.

Cool, thanks for the replies, :). I'll look into arrays further, I had considered that idea but thought perhaps there was something more efficient such as my one-line call. Oh well. I'm enjoying this the further I dive in, I just hope I'll be able to grasp more advanced concepts in future.

One question that has been partially in my way while I make this console app; can I link to external classes? What I mean is in my project all my code is in the default Program.cs, can I trim down the amount of code and keep it tidy by having things like profile building in a Profile.cs, and link it into the main Program.cs where the rest of the game code will be? I'm trying to keep it from becoming bloated as I build it so I don't end up dealing with it later on.

One question that has been partially in my way while I make this console app; can I link to external classes?

Yes, you certainly can. If you make it part of your project in the same namespace it's even more straightforward, as you just need to make an instance of the class.

Cheers, I'll investigate that when I get back into it. For the moment I'm progressing deeper into PHP to try and develop more, :).

I would begin by designing something that could become quite large.

I don't mean full scale design though.

For example. I would treat everything as a GameObject where GameObject has some basic data like "Description", "Position" etc and some basic functionality like "PrintDescription", "Push", "Pull" etc.

Then specify more; so if you had a Banana and a Room.

public class Banana : GameObject
{
    // Still have all GameObject methods etc
    StepOn(){ Console.WriteLine("You slipped on a banana!");
}

public class Room : GameObject
{
    // Still have all GameObjects basic stuff
    public WalkNorth();
    public OpenDoor(int doorNumber);
}

etc etc.

This way you can componentise just about every aspect, meaning less repeated code.
(eg. you only have one PrintDescription method rather than 20 with different text in)

I would bear this in mind when you start coding it again =)

commented: Good job. Stimulating newbies to prevent the coding with desing would save a lots of time :) +2

Yes, I had been encouraging the OP towards that idea. He hasn't really done any OOP in C# (or perhaps at all). Now we've lost him to PHP...

PHP is becoming more OO...It is! Really!...

I know I'm deluding myself ^^

You haven't lost me to PHP. I'm interested in software development but my job is in web development, so progressing further in that is above my new hobby of C#, unfortunately... I haven't really got a good grasp on the whole namespace, class and method structure just yet, I'm still stuck in my web design mentality of classes as being more functions, with methodology within them, and nothing above the functions. That's why I couldn't quite put into words what I was looking for in my initial post, :$. I'll get there, I'm actually going to do some C# tomorrow I think, as I went a bit overboard on PHP the other day...

Will keep you all posted, thanks to you both for more the further explanation.

If I read it correctly, would I be able to use GameObject.Banana.StepOn(), and it'd write what's in the WriteLine? Or did I totally misread that, ha ha? I think I understood the 'public OpenDoor(int doorNumber);' easily enough, as there'd be something with doorNumber set to a number, and it'd make the doorNumber value an integer, right? So it'd run OpenDoor(1), and that'd have some functionality occurring (methods?). I don't know, I think I might start the book over in the first chapter instead of beginning the console application until I grasp the fundamentals I bit better...

Ok I'll give a quick lesson on classes and inheritance.

(This will come in handy for your PHP as PHP5 and above uses classes also)

If we ignore the fancy definitions for a minute and go back to something more common in English.

Think of a class as an object. Something that is sat on your desk (not the C# keyword).
Your keyboard for example. Let's say we want to make a class out of your keyboard

public class MyKeyboard
{
    Keyboard();
}

The empty Keyboard function you see there is the Constructor. At the moment it doesn't do anything, but it gets called whenever you "make" (instantiate) a keyboard.

So consider what your keyboard is like. It has a colour and it has keys.
So we modify the keyboard class to represent this.

public class MyKeyboard
{
    Keyboard();
    public Colour KeyboardColour;
    public List<String> KeyboardKeys = new List<String>();
}

(If you don't know what a list is, it's like an array, but you can make it grow or shrink as you need to)

As you can see we can now assign the keyboard a colour and give it some keys represented as strings ("Q", "W", "E", "End", "Escape" etc)
Things your keyboard HAS are called Properties and are your individual bits of data that describe your class. A person would have the following properties, Name, Age, Height, Job and then some.

Ok so now consider what can you keyboard do. You can press your keys...That's pretty much it for a basic keyboard...

public class MyKeyboard
{
    Keyboard();
    public Colour KeyboardColour;
    public List<String> KeyboardKeys = new List<String>();

    public void KeyPressed()
    {
        Console.WriteLine("You pressed a key!");
    }
}

So as you can see, methods describe what this object can DO

I mentioned a Person as a class before. So let's draw that one up

public abstract class Person
{
    public String Name;
    public Int32 Age;
    public Double Height;
    public String Job;

    public abstract void Walk();
    public void Say(String sentence)
    {
        Console.WriteLine(Name + " says: " + sentence);
    }
}

If you look over the above class you see we've created a Person object. They have a name, age, height and job. They can walk and say.

You'll notice a new keyword: abstract

This means that this class cannot be instantiated alone.
So I can't do this Person john = new Person(); This means the class must be inherited. Any methods that are marked abstract, must be replaced (overridden) by whatever class is inheriting it.

To inheriting means just that, the class that inherits, now gets all the properties and methods of the sub-class (in this case, the Person class is our sub-class)

So lets make a Parent class

public class Fireman : Person
{
    public Fireman(String name, Int32 age, Double Height, String job)
    {
        Name = name;
        Age = age;
        Height = height;
        Job = job;
    }

    public override void Walk()
    {
        Console.WriteLine(Name + " walked forwards");
    }
}

So as you can see, we've got a Fireman class that inherits the Person class.

To know whether you should Inherit or Contain (put in the class) there's a little rule: is-a or has-a

If you can say something "is-a" you should inherit. If you can say something "has-a" you should contain it.

A Fireman "is-a" Person. A Person "has-a" name.

Ok so now we've inherited and created our Fireman class we should instantiate him. Notice that our Constructor takes 4 parameters: Fireman john = new Fireman("John", 25, 180, "Primary Hose Spraying Guy"); We now have a fireman named john who is 25, 180cm tall and his job is the primary hose spraying guy.

john.Walk();
john.Say("Turn on the water!");

would produce the output:

John walks forward
John says: Turn on the water!

But the good thing about inheritance is that we can do it again, with another class. As an exercise for yourself, make a policeman class that inherits Person. This police man can also, apart from walk and say, arrest people. So add a method for that in and some suitable vocab.

That's pretty much it for my quick lesson on classes and inheritance =)

commented: Very helpful post, helping me wrap around code that I'm new to. Thanks again! +1

So KeyboardColour needs a colour assigned to it, so then it reads that the Colour element of MyKeyboard = the colour chosen? Inheriting the person class means that Fireman is able to be called just as Person is, but values assigned to the name, age etc in Fireman are only assigned to Fireman, is that correct?

So the public override void walk() is like defining a function, and what's within is what's 'run' when the function is called? That bit seemed easier to interpret as I've done similar in jQuery.

I think I understand your lessons...

Yeah pretty much.

The Person has "Name" and Fireman has inherited Person. So all of the Person class (that hasn't been marked private) is available to Fireman. public String Name; is accessible to Fireman
If we added a private variable to Person called PersonId... private int PersonId; is NOT accessible to Fireman

Yes. If you override a function, when you call that class's function. public override void Walk(){ // stuff } When you called Fireman.Walk() that method is run.

You can if you choose, decide to call the base class method instead. public override void Walk() { base.Walk(); } This will call Person.Walk().

You can also cast Fireman to Person...

Fireman sam = new Fireman();
sam.Walk(); // Fireman.Walk();
Person thisPerson = (Person)sam;
thisPerson.Walk(); // Person.Walk();

The above code will only work if Person is not an abstract class.

Cool, thanks for helping me wrap my head around that. I'm not the best with programming structure and syntax across languages, I seem to only learn how things apply to the examples they're used in, which sucks because I'm limited. I'll be putting this to good use, thanks again. +rep to you and jonsca for the patient assistance. Would it be alright if I had further questions in future to PM you direct? I promise I won't make too many, :P.

If you have queries make threads. This is a community site so keeping potential help from other people is something I don't agree with =)

To know more from here there's a lot of tutorials on the web that can help you. Or you can get a decent programming book from Amazon or your local shop.

If you have queries make threads. This is a community site so keeping potential help from other people is something I don't agree with =)

I don't either, I hadn't thought of that! I'd only thought that all my questions were too basic and would distract people from other topics. Topics it is then, :).

I've got a C# book but it's primarily to do with Game Development... perhaps I should get one that's teaching C# in general so it isn't as limiting as this one seems to be thus far.

EDIT: Double posted somehow...

Thanks for the book references, I'll see if my local Borders has them and will pick one up.

I'll mark this as solved now. Thanks to all contributors, I'm pretty sure each of you got +1 rep points, if I seemed to somehow miss you just PM me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.