Implicitly Typed Arrays in C#

C# certainly composed arrays: Here, we will find out about the verifiably composed arrays in C#, how to announce a certainly composed array in C#?

C# Implicitly Typed Arrays

Like certainly composed variables, we can likewise announce an array without determining its sort such kind of arrays are known as Implicitly composed arrays.

The kind of the array is controlled by the compiler dependent on the initializer list.

Syntax:

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

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[] { "Aakash", "Durgesh", "Kishan", "Vivek", "Vikas" };

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

C# code to exhibit an example of verifiably composed arrays:

using System;
using System.Text;

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...
Aakash Durgesh Kishan Vivek Vikas

Leave a Comment

error: Alert: Content is protected!!