When do i use new ?

I’m new to programing and i wanna know when to write new.

For example:

x = y; or x = new y;

Can someone explain what new means please ?

Ok let me simplify this as much as possible. First of all, I highly recommend you watch and follow the Unity beginner programmer videos. They are definitely going to help you, it is also a very clean, consistent and FREE way to learn programming :slight_smile:

new is used for creating objects. Your example doesn’t really make sense because y is a variable, not a type. Also you didn’t provide us with what type you are using.

So, if you can do x = y;, you definitely cannot do x = new y; (also note that should by x = new y();).

In C#, you use new when creating objects. It is a garbage collected language, which means you do not have to release memory yourself. Issues of stack vs. heap are a more advanced concept that I would not worry too much for now, until you get a good grasp on the language. The notation comes from C++, but is used to make it clear what you want to do. Class1(); could be a function or a method call, new Class1(); makes it clear you are initializing an object.

Simply put: Use new to create objects. MyObject potato = new MyObject(); If you want to assign an object, like in your example, then you do not use new as the object is already created. You are simply copying the object and it’s values potato = tomato;. Note that the reality is a little more complex, but in practice this will work as you expect.

Once you understand more concepts of programming, scope, initializing your objects etc. Then I would google various topics related to: C# references, C# new, C# structs, C# classes, C# stack heap, C# initialization. These should all be related to what you are asking, but are a little bit too advanced for now I believe.

Some doc:


Great article on references and stack/heap. I would read the first part at least: Value vs Reference Types in C#