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,341 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
174,115 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,473 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