Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Objects Object-Oriented Programming Object Initialization

Ruslan T
Ruslan T
1,706 Points

Game.cs(9,21): error CS0122: `TreehouseDefence.Map.Map(int, int)' is inaccessible due to its protection level

I'm getting this error whenever I'm trying to compile the code. Any ideas?

Game.cs(9,21): error CS0122: `TreehouseDefence.Map.Map(int, int)' is inaccessible due to its protection level

Game.cs -

namespace TreehouseDefence { class Game { public static void Main() { Tower tower = new Tower();

      Map map = new Map(8,5);

      int area = map.Width * map.Height;

    }
}

}

Map.cs -

namespace TreehouseDefence { class Map { public readonly int Width; public readonly int Height;

Map(int width, int height)
{
  Width = width;
  Height = height;
}

}

}

2 Answers

Steven Parker
Steven Parker
229,744 Points

The "protection level" is determined by the access modifier in the declaration. When there is none, as in this case, the default level is "private". To make the constructor available, it should have the "public" access modifier.

    public Map(int width, int height)

And when posting code in the forum, use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.

I had this same issue as well and had to add the public keyword to the constructor method as well. It is a bit confusing because he leaves that keyword off in the video. I'm not sure why his code compiled, because it should have thrown the same error.

Steven Parker
Steven Parker
229,744 Points

Perhaps the method is only defined at that point in the video and never called. The access issue would only arise when another module attempts to reference that method.