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 Fields

jamesroyle
jamesroyle
2,621 Points

Why do we type "Map map = new Map();"

I understand that this is creating a new object of the class Map. But i don't understand why we have the first Map. I feel like it should be this:

map = new Map();

Why do we write Map twice? It seems like we are referring to the class twice.

Fredrik Rönnehag
Fredrik Rönnehag
2,342 Points

First Map is the reference type, like writing string yourName = "Name"; Then you are typing new Map(); to tell the computer to create a new instance of the class Map.

2 Answers

Steven Parker
Steven Parker
231,198 Points

You still need to declare the type of thing you are creating with the name "map". But instead of explicitly naming "Map" as the type you can let the compiler figure it out from the assignment by using the keyword "var":

var map = new Map();
Stivan Radev
Stivan Radev
1,475 Points

When you type map = new Map(); > You get an error says that the name 'map' does not exist in the current context.

But when you type Map map > it is saying that the class Map has a new variable 'map'.

You can test it out for yourself and you might understand it. That is what I just did. And also that is why I can't explain it better but just know one thing.

Whenever you are making a new class, lets say Map, also include 'Map' in front of 'map = new Map();' because if you do not you will get an error saying, 'map' does not exist in the current context.

Sorry for the bad explanation, but do try it out for yourself and see what you wil get!

Good Luck