C# Implicitly Typed Arrays

C# implicitly typed arrays: In this tutorial, we will learn about the implicitly-typed array, its definition, usage, declaration, and examples. By IncludeHelp Last updated : April 11, 2023

Implicitly Typed Arrays

Like implicitly typed variables, Implicitly-typed arrays are declared without specifying their types and they are usually used in query expressions with anonymous types and object and collection initializers. The type of the array is determined by the compiler based on the initializer list.

Implicitly Typed Array Declaration

The following syntax shows declaration of an implicitly-typed array,

var array_name = new[] {initialize_list/elements};

For example,

var arr1 = new[] { 10, 20, 30, 40, 50 };
var arr2 = new[] { 10.0f, 20.1f, 30.2f, 40.3f, 50.4f };
var arr3 = new[] { "Manju", "Amit", "Abhi", "Radib", "Prem" };

Here, arr1 will be determined as int[] (integer array), arr2 as float[] (float/single array), and arr3 as String[] (string array).

C# Example of Implicitly Typed Arrays

using System;

namespace Test {
  class Program {
    static void Main(string[] args) {
      var arr1 = new [] {10,20,30,40,50};
      var arr2 = new [] {10.0f, 20.1f, 30.2f, 40.3f, 50.4f};
      var arr3 = new [] {"Manju","Amit","Abhi","Radib","Prem"};

      //printing type of the array
      Console.WriteLine("Type of arr1: " + arr1.GetType());
      Console.WriteLine("Type of arr2: " + arr2.GetType());
      Console.WriteLine("Type of arr3: " + arr3.GetType());

      //printing the elements
      Console.WriteLine("arr1 elements...");
      foreach(var item in arr1) {
        Console.Write(item + " ");
      }
      Console.WriteLine();
      
      Console.WriteLine("arr2 elements...");
      foreach(var item in arr2) {
        Console.Write(item + " ");
      }
      Console.WriteLine();

      Console.WriteLine("arr3 elements...");
      foreach(var item in arr3) {
        Console.Write(item + " ");
      }
      Console.WriteLine();

      //hit ENTER to exit
      Console.ReadLine();
    }
  }
}

Output

Type of arr1: System.Int32[]
Type of arr2: System.Single[]
Type of arr3: System.String[]
arr1 elements...
10 20 30 40 50
arr2 elements...
10 20.1 30.2 40.3 50.4
arr3 elements...
Manju Amit Abhi Radib Prem



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.