What is the difference between initialization and assignment of values in C#?


Let us understand the difference between initialization and assignment of values.

Declaring an array.

int []  n  // declaring

Initialization

Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array. Array is a reference type, so you need to use the new keyword to create an instance of the array.

int n= new int[10]; // initialization

Let’s assign value. You can assign values to individual array elements, by using the index number −

n[0] = 100;
n[1] = 200

With C#, you can declare, initialize and assign values to an array in a single line −

int n= new int[10] {100, 200, 300, 400, 500};

When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0.

Updated on: 30-Jul-2019

802 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements