How to assign multiple values to same variable in C#?

CsharpProgrammingServer Side Programming

To set multiple values to same variable, use arrays in C#. Let’s say instead of taking 5 variables, set these 5 variables using arrays in a single variable.

The following is an example to set three values to a single variable with a string array −

string[] arr = new string[3];

Let us now initialize it −

string[] arr = new string[3] {"one", "two", "three"};

The following is the complete example −

Example

 Live Demo

using System;

public class Demo {
   static void Main(string[] args) {

      string[] arr = new string[3] {"one", "two", "three"};

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

      Console.ReadKey();
   }

}

Output

Values: one
Values: two
Values: three
raja
Published on 07-Aug-2018 12:44:17
Advertisements