Error: member names cannot be the same as their enclosing type

Muhammad Sohail picture Muhammad Sohail · Feb 7, 2014 · Viewed 22.2k times · Source

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

Answer

Dr Rob Lang picture Dr Rob Lang · Feb 7, 2014

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!