CSharp - Array element default value

Introduction

The elements of an array are initialized to their default values.

int is a value type and its default value is 0.

a string is a reference type. The string array (myStringArray) is initialized with null references.

Demo

using System;

class Program// ww w. j a  va  2  s.  com
{
    static void Main(string[] args)
    {
        int[] myIntArray = new int[4];
        for (int i = 0; i < myIntArray.Length; i++)
        {
            Console.WriteLine("myIntArray[" + i + "] is : {0}", myIntArray[i]);
        }
        string[] myStringArray = new string[4];
        for (int i = 0; i < myStringArray.Length; i++)
        {
            bool value = string.IsNullOrEmpty(myStringArray[i]);
            if (value)
            {
                Console.WriteLine("myStringArray[" + i + "] is null.");
            }
            else
            {
                Console.WriteLine("myStringArray[" + i + "] is NOT  null.");
            }
        }
    }
}

Result

For the reference type, we need to explicitly instantiate them.

We can instantiate the elements of the string array (myStringArray) like this:

myStringArray[0] = "abc";

Related Topic