C# Array - Fill() Method



The C# Array Fill() method is used to populate the given value of type 'T' to each element of the specified array. Which are within the range of startIndex (inclusive) to the next count indices.

Syntax

Following are the syntax of the C# Array Fill() method −

public static void Fill<T>(T[] array, T value);
public static void Fill<T>(T[] array, T value, int startIndex, int count);

Parameters

This method accepts the following parameters −

  • array: An array to be filled.
  • value: The value that should be assigned to each element in the specified array.
  • startIndex: It represents the index in the array at which populating starts.
  • count: The number of elements to copy.

Return value

This method does not returns any value.

Example 1: Fill the Entire Array

This is the basic example of the Fill() method to populate he entire array with value 10 −

using System;
class Program
{
   static void Main()
   {
      int[] numbers = new int[5];
      
      Array.Fill(numbers, 10);

      Console.WriteLine(string.Join(", ", numbers));
   }
}

Output

Following is the output −

10, 10, 10, 10, 10

Example 2: Fill Part of an Array

This is another example, uses the overloaded Fill() method to fill part of the array −

using System;
class Program
{
   static void Main()
   {
      int[] numbers = new int[10];
      
      Array.Fill(numbers, 7, 2, 5);

      Console.WriteLine(string.Join(", ", numbers));
   }
}

Output

Following is the output −

0, 0, 7, 7, 7, 7, 7, 0, 0, 0

Example 3: Fill an Array of Strings

Let's see another example of the Fill() method to populate the array with strings −

using System;
class Program
{
   static void Main()
   {
      string[] fruits = new string[4];
      
      Array.Fill(fruits, "tutorialspoint");
	  
      Console.WriteLine(string.Join(", ", fruits));
   }
}

Output

Following is the output −

tutorialspoint, tutorialspoint, tutorialspoint, tutorialspoint

Example 4: Fill an Array of Custom Object

The below example usesthe Fill()method to populate an array with the custom object −

using System;

class Person
{
   public string Name { 
     get; 
     set; 
   }
   public int Age { 
     get; 
     set; 
   }

   public override string ToString() => $"Name: {Name}, Age: {Age}";
}

class Program
{
   static void Main()
   {
      Person[] people = new Person[2];
      
      // Fill the array with a default person
      Array.Fill(people, new Person { Name = "tutorialspoint India", Age = 10 });

      foreach (var person in people)
      {
         Console.WriteLine(person);
      }
   }
}

Output

Following is the output −

Name: tutorialspoint India, Age: 10
Name: tutorialspoint India, Age: 10
csharp_array_class.htm
Advertisements