Keyword "new" in C#

Asked

Viewed 359 times

2

I went to see about the keyword new in C#, but I could not find someone who explains well what I want to know. They say that the new creates a new instance, but I don’t understand exactly what they mean by "creating an instance".

2 answers

5


Roughly speaking we can say that an instance is an object. In this case we are saying that it is creating an object of a specific type.

When we write the code we create two things, a data structure and algorithms that operate these structures. In languages that adopt object orientation it is common for these two things to be written together forming a type. This type can be a class, but it doesn’t always need like this, it has other ways of organizing the data and the algorithms that form a type.

Whenever we want to create an object we use a model of how this object is created.

When we want to create an object we say which type this object will be, then we call the type constructor (one of them, because it can have more than one)but not to be confused with a normal method call and also to make it clear that there will be a memory allocation at that point we also use the new before the name of the manufacturer.

Not to be confused with another new existing in language.

Some things you might be interested in:

  • So for example: I have this: public class Example { private Example ex = new Example() } That means I created a new address in memory for this new instance class ex with the new constructor values(in case I have not put any value then it invokes the default constructor). That’s it?

  • It is basically this, although the correct form is a little different, would need to understand other previous concepts to be able to understand these more advanced.

  • Thank you! It helped a lot!

  • Just one more thing... I decided to complement what I think is the New... for example... public class Example { int A = 2 Example (int a) { int a = A} private Example Ex = new Example() } I created a new memory address for the class Example, and as the Ex instance is of the Example type it can be stored in the same memory location as the Example... with the new values of the constructor... but inheriting everything from the Example class, because they are in the same memory location... is now correct? Something is missing?

  • new does not create memory addresses, addresses exist by themselves. You have not read my answer carefully. I said that it creates an object, not address. How can two bodies occupy the same place in space? We speak nothing of inheritance, new This is not part of the scope of what we are talking about. All your concepts are wrong. Perhaps it was the case to ask another question with all these details, and reinforce the idea of detailing very much everything, if possible by examples, present all your understanding, and all doubts

  • Since that related, otherwise it has to be separate questions. This question needs to be very well asked to be accepted on the site. Also reinforce that basic understanding is missing before knowing about the new.

  • So I think all my concepts about C# itself are wrong... or at least in this area of instances... I think I’ll create a new question...

  • @Gatti but for this problem the answer is already ok? See the [tour] what you can do. You can accept the answer and vote for it too. Vote you can give on everything on the site.

  • Okay... I came back. And a little more... I’ve actually finished several courses online, it’s been 6 months that I see about programming, and I know how to use C# very well... the problem is that in none of these courses define "instance" or "New" You end up using them without knowing what they do...and so there are some "holes" in my understanding of C#. And although your answer is very good, I still can’t quite understand what "New" does... I have a very solid base in C#, for example I know how to use "New", but I don’t know what it does in the system... I hope I gave to understand.

  • I told you that’s not how the site works and I’ll send you one more thing to help you: https://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect

Show 5 more comments

2

Before understanding the operator’s concept new it is necessary to understand well what is a variable.
Then it is necessary to understand the basic concept of structures and classes.


In general terms, a variable is the mechanism in the programming to store (and access) in memory some value that will be used again at some point of the program.

Examples of variables of "simple types" (read note at the end of the reply):

int   i = 123;
float f = 1.23F;
bool  b = true;
char  c = 'X';

The code above defined four variables, i, f, b and c. They are variables because the value they store can vary, can be changed, along their lives. Already the values assigned to them, 123, 1.23F, true and 'X', sane constant, because 123 will always be 123, it is not possible to change it.

As I said, a variable stores a value in memory, then, when you define a variable as int i;, what happens behind the scenes is that the computer checks which address in memory is available to store a type int, for example 0x12345000 (notation for a number hexadecimal), and assigns that address to the variable i. Like the guy int occupies 4 bytes, at that time the address range in the memory of your program 0x12345000 to 0x12345003 will be reserved for your variable i. When you assign some value to that variable, the program will store that value in that memory address, and when you refer to the value of that variable, the program will fetch the value stored in that memory address.

These examples I mentioned are "simple types", but there are also more complex types, such as structures and classes.


Basically, a structure is a grouping of variables, which serve the same purpose.

Example of definition of a structure:

public struct Point
{
   public int X;
   public int Y;
}

And a class is also, in a way, a grouping of variables that serve the same purpose (when these variables are internal we call fields, when they can be accessed from outside the class we call estates, roughly), but also a grouping of functions that serve that purpose (called methods). In C# a structure can also have properties and methods, but there are differences between.

Example of definition of a class:

public class MinhaClasse
{
   private int meuCampo;

   public int MinhaPropriedade
   {
      get { return this.meuCampo; }
      set { this.meuCampo = value; }
   }

   public int MeuMetodo()
   {
      return this.meuCampo * 2;
   } 
}

But even when we use these more complex types, the same concept of variable remains valid: the variable is a name given to a memory address that is storing our values (in the case of classes the variable actually stores a reference to another address in memory, which contains our values, in fact, but, let’s keep the idea simple).

The definition of a structure or class does not contain variable values (but can contain constant values), because it is only a model, an "empty shell without content". When we want to use this model (structure or class) we create a object, that is an instance of an object type (object type = structure or class). Here we are assigning "content to the empty shell".

Our variable in this case will then be our means of access to the address of the memory in which our object is stored (or the reference to our object). Like any other variable, throughout its life it can receive other values, ie other objects. So:

// Atribui à minha variável um objeto que já existe.
MinhaClasse meuObjeto = outroObjetoDoMesmoTipo;

Finally answering the question:

But when we want to create a new object, one that does not yet exist, we must use the operator new:

// Cria um novo objeto e atribui à minha variável.
MinhaClasse meuNovoObjeto = new MinhaClasse();

This new object will probably come with all zeroed values (or their default constant values, which may be non-zero), unless our type (structure or class) has a builder initialize our new object with values informed at the time of its creation, with the operator new.


Note about "simple types"
At the beginning of the answer I quoted the types int, float, bool and char as simple types, and they really are considered so (documentation), so much that they don’t need the operator new to create a new object of these types, but in C# even these simple types are, in the background, structures.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.