Home > Net >  How to call public class from main console?
How to call public class from main console?

Time:06-16

so I'm creating a small program and am having trouble calling a public class from my main console. In the main console, the class is to be called if the user selects a certain choice. The class is called within an if-statement if(choice == "1"} {(class is called)}. I'll also note there's a return statement at the bottom of the second class. Here's what the first three lines of the separate class look like:

string actChoice = Console.ReadLine();

        if (actChoice == "2")
        {
            class Kitchen; 
   

        }
class Kitchen
{
    //this class will be played when you choose 2
    public class Ren
    {
        //setting method 
        public void Meal()

CodePudding user response:

If you want to use a class you need to create a new instance of that class. Unless this class is static, and in that case everything inside it (methods fields etc..) should be static as well.

How to create a new class for example:

var kitchenInstance = new Kitchen();

So this is how you should do it:

string actChoice = Console.ReadLine();

if (actChoice == "2")
{
    var kitchenInstance = new Kitchen(); 
}

class Kitchen
{
    //this class will be played when you choose 2
    public class Ren
    {
        //setting method 
        public void Meal()
        {
        }
    }
}

Watch a few videos on classes and some example of them to strengthen your knowledge about them.

CodePudding user response:

string actChoice = Console.ReadLine();

switch (actChoice)
{
    case "1":
        
        break;
        case "2":
            Kitchen.Ren ren = new();
        ren.Meal();
        break;
    default:
        break;
}
class Kitchen
{
    public class Ren
    {
        public void Meal()
        {
            Console.WriteLine("OK Meal");
        }
    }
}
  • Related