Question

I am new to C#, I am learning it and it is just a dummy test program. I am getting the error that is mentioned in the title of this post. Below is the C# code.

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

namespace DriveInfos
{
    class Program
    {
        static void Main(string[] args)
        {
            Program prog = new Program();
            prog.propertyInt = 5;
            Console.WriteLine(prog.propertyInt);
            Console.Read();
        }

        class Program
        {
            public int propertyInt
            {
                get { return 1; }
                set { Console.WriteLine(value); }
            }
        }
    }
}
Was it helpful?

Solution

When you do this:

Program prog = new Program();

The C# compiler cannot tell if you want to use the Program here:

namespace DriveInfos
{
    class Program  // This one?
    {
        static void Main(string[] args)
        {

Or if you mean to use the other definition of Program:

    class Program
    {
        public int propertyInt
        {
            get { return 1; }
            set { Console.WriteLine(value); }
        }
    }

The best thing to do here is to change the name of the internal class, which will give you:

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

namespace DriveInfos
{
    class Program
    {
        static void Main(string[] args)
        {
            MyProgramContext prog = new MyProgramContext();
            prog.propertyInt = 5;
            Console.WriteLine(prog.propertyInt);
            Console.Read();
        }

        class MyProgramContext
        {
            public int propertyInt
            {
                get { return 1; }
                set { Console.WriteLine(value); }
            }
        }
    }
}

So now there is no confusion - not for the compiler, nor for you when you come back in 6 months and try to work out what it is doing!

OTHER TIPS

You have two classes with the same name Program. Rename one of them.

namespace DriveInfos
{
    class Program
    {
        static void Main(string[] args)
        {
            Program prog = new Program();
            prog.propertyInt = 5;
            Console.WriteLine(prog.propertyInt);
            Console.Read();
        }

        class Program1
        {
            public int propertyInt
            {
                get { return 1; }
                set { Console.WriteLine(value); }
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top