Why not define data type in vector?

BrunoB

Well-known member
Joined
Nov 19, 2022
Messages
96
Programming Experience
Beginner
Hello how are u?this is my question,i dont understand. Thabks.
image.png
 
Calling new Articulo[10] just creates a reference to array that can contain references to 10 Articulo. You still need to populate the array by allocating each Articulo and storing the reference in the array. Java works the same way.

If you were expecting C++ like behavior where the 10 Articulos are also created at the same time, it is time to review what you have learned about C# arrays. They only time C# will allocate those 10 Articulos will be if Articulo is a value type instead of a reference type. (E.g struct vs. class)
 
C#:
Articulo[] articulos = new Articulo[10];

It is the array you have made anew, not the things inside it..

It is like you have done this:

C#:
Articulo articulo0;
Articulo articulo1;
Articulo articulo2;
Articulo articulo3;
Articulo articulo4;
Articulo articulo5;
Articulo articulo6;
Articulo articulo7;
Articulo articulo8;
Articulo articulo9;

Of course, this will still crash:

C#:
articulo6.CodigoMarca = 3;

Because all you did was make a slot in the computer's memory capable of holding an Articulo. You didn't actually make an Articulo
 
I tend to think of arrays as being like egg cartons. The fact that you create an egg carton doesn't mean that you can magically make an omelette. Putting the eggs into the carton is a separate operation to creating the carton.
 
Like that.

I've come to think of them as like normal variables, but with a part of the name that can be programmatically varied ..

.. mainly because newbies start off with

C#:
var p = new Person();

Then they go to

C#:
var p1 = new Person();
var p2 = new Person();
...

Then they start asking how they can use loop to generate the 1 and the 2

C#:
for(int x =  1; x<=2; x++){
  Console.Write((p+x).Name);
}

Or some similar wonky..

..so they seem down with being able to fabricate a name using a fixed part and a varying part, they just didn't yet make the leap to the varying part being in square brackets..
 
well, supposedly an array is defined with data type x eg int[] array name= new int[n]..here it doesn't say if it's float,double or ,etc...that's what my question was about
 
If type x is a reference type, you need to fill in the egg carton as mentioned above.

If type x is a value type, the carton comes pre-filled.
 
well, supposedly an array is defined with data type x eg int[] array name= new int[n]..here it doesn't say if it's float,double or ,etc...that's what my question was about
The data type is there:
int[] array name= new int[n]

"int" is the data type

Float would be:

float[] arrayName = new float[n]



 

Latest posts

Back
Top Bottom