Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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); }
            }
        }
    }
}
like image 264
Muhammad Sohail Avatar asked Feb 07 '14 14:02

Muhammad Sohail


1 Answers

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!

like image 177
Dr Rob Lang Avatar answered Nov 03 '22 00:11

Dr Rob Lang