int array

  • Thread starter Thread starter RicercatoreSbadato
  • Start date Start date
R

RicercatoreSbadato

When I do

int[] array = new int[256];

the array is still cleared or I have to set all the values to 0?
 
Hi Ricercatore

The array is clear when created using the new operator

using System;
class Test
{
static void Main()
{
int[] arr = new int[5];

for (int i = 0; i < arr.Length; i++)
Console.WriteLine("arr[{0}] = {1}", i, arr);
}
}

prints out fives zeroes.

Hope this helps

Publicjoe

C# Tutorial at http://www.publicjoe.f9.co.uk/csharp/tut.html
C# Ebook at http://www.publicjoe.f9.co.uk/csharp/samples/ebook.html - 74
Chapters
VB Ebook at http://www.publicjoe.f9.co.uk/vbnet/samples/ebook.html - 30
Chapters
C++ Ebook at http://www.publicjoe.f9.co.uk/cppt/samples/ebook.html - 8
Chapters
Java Ebook at http://www.publicjoe.f9.co.uk/java/samples/ebook.html - 2
Chapters
Mirrors at http://dowhileloop.com/publicjoe/ and
http://publicjoe.justbe.com/

Blog - http://publicjoe.blogspot.com
 
When you create an array of a particular type all the elements in that type
are set to their default value. The default value for int is 0 so all the
elements of "int[] array = new int[256];" will be 0 to start with.

All the elements of "string[] array = new string[256];" would be null as
null is the default value for a string.

Hope this helps.
 
Arjen said:
RicercatoreSbadato said:
When I do

int[] array = new int[256];

the array is still cleared or I have to set all the values to 0?

I think they are all null (not 0).

This is not the case. In fact, a variable of any value type, including many
primitive types such as int, can never have a null value. They are all set
to 0, the default value for int. You can read more about initialization in
C# here:

http://www.jaggersoft.com/csharp_standard/12.2.htm
http://www.jaggersoft.com/csharp_standard/17.4.4.htm
http://www.jaggersoft.com/csharp_standard/12.1.7.htm (paragraph 3)

Be warned that in some cases this "defensive" type of default-value
initialization can hide bugs. Consider adding a method for testing to mess
up the values of these variables. If you're relying on default-value
initialization, always make this explicit. I hope this helps.
 
Back
Top