I'm new to c# but i really want to understand about the "new" keyword in c# to know how to use it in future, i've seens alot of basic video about c# using new keyword but i just copy them without any knowledges and it makes my quite uncomfortable, i've searched it on google alot but only understand a few things, the most hardest thing for me to understand is "it creates a new empty object", can someone explain it for me?
And why i can't just create an object like this if i don't have any constructors
Class1 student = Class1(); //i got an error with this but it's still not help me understand the new keyword
When will i need to create an array like this
string[] myArr = new string[0];
not like this
string[] myArr = {};
It'll be nice if someone can give me some easy-to-understand example :P Everytime i searching about the new keyword, my brain just overthinking it :'D
There is a difference between Classes and Objects. Objects are an instantiation of a Class.
For example, if you have a House
class, you can have multiple House
-objects based on it.
Every time you want to create (in the analogy: build) a new house, you have to use the new
keyword.
For example:
House myHouse = new House();
myHouse.openDoor(); //Opens the door of house 1
House neighboursHouse = new House(); //My neighbour likes to live in a house too, but I dont want him in my house. I create a new House.
neighboursHouse.ringDoorbell() // I don't have a key to my neighbours house.