Home > Net >  Name '...' doesn't exit in current context
Name '...' doesn't exit in current context

Time:12-08

I am a beginner in C# right now and my task is to write in console all the details of a product. I have to use the struct. I made a Product struct. The function writeProducts cannot see the prod1 and all of its details.

However I get an error CS0103 that the name doesn't exist in current context and I don't know where I made a mistake.

Sorry, English is not my native language.

namespace project
{
    class Program
    {
        public struct Product
        {
            public string Name;
            public string Type;
            public double Pr1pc;
            public double Pr1kg;
            public int number;
        }
       
        static void Main(string[] args)
        {
            Console.Clear();
            Product prod1;

            //Prod1
            prod1.Name = "Chlyb";
            prod1.Type = "szt";
            prod1.Pr1pc = 6.30;
            prod1.number = 1;

            writeProducts();

            Console.ReadKey();
            Main(args);
        }
        static void writeProducts()
        {
            Console.WriteLine("{0}. {0},{0}{0}", prod1.number, prod1.Name, prod1.Pr1pc, prod1.Type);
        }
    }
}

CodePudding user response:

You declared the variable prod1 in the Main function, so it is not recognized in the writeProducts function. Try to send the prod1 as a parameter to writeProducts like that:

class Program
    {
        public struct Product
        {
            public string Name;
            public string Type;
            public double Pr1pc;
            public double Pr1kg;
            public int number;
        }

        static void Main(string[] args)
        {
            Console.Clear();
            Product prod1 = new();

            //Prod1
            prod1.Name = "Chlyb";
            prod1.Type = "szt";
            prod1.Pr1pc = 6.30;
            prod1.number = 1;


            writeProducts(prod1);


            Console.ReadKey();
            Main(args);



        }
        static void writeProducts(Product prod)
        {

            Console.WriteLine("{0}. {0},{0}{0}", prod.number, prod.Name, prod.Pr1pc, prod.Type);
        }
    }
}

Also notice you need to use the new word when declaring prod1

  • Related