Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Name '…' doesn't exit in current context

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
        }
    }
}

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading