Different ways of array declarations in C# [closed]

What is the difference between the following two methods of creating an array in C#:

  • int[] arr = new int[] { 1, 2, 3 };

  • Array arr = new int[] { 1, 2, 3 };

The first form creates an array of integers. The second form creates an array of something.

The major difference is that the first variant gives you, the developer, the explicit indication of the type of objects stored in the collection. This indication will help both at the moment of writing code if you use an IDE with IntelliSense, and at the moment when the code is compiled. For instance, you won’t be able to add a string to a sequence if integers. The following code won’t compile:

var arr = new [] { 1, 2, 3 };
arr[1] = "Hello World"; // CS0029 Cannot implicitly convert type 'string' to 'int'

On the other hand, with Array, you can’t use indexes to change the values of the elements:

Array a = new [] { 1, 2, 3 };
a[1] = "Hello World";
// CS0021 Cannot apply indexing with [] to an expression of type 'Array'

which forces you to set the value like this:

Array arr = new [] { 1, 2, 3 };
arr.SetValue("Hello World", 1);

This code will actually compile, but fail during runtime with an InvalidCastException.

So unless you actually need to suppress the indication of the type (and I can hardly imagine a case where you would need that), just use:

var arr = new [] { 1, 2, 3 };

and let the IDE and IntelliSense help you enforcing the types.

Note that an array of something is not the same thing as an array of objects. In order to understand the difference, try to run the following piece of code:

var arr = new object[] { 1, 2, 3 };
arr.SetValue("Hello, World!", 1);

See? No runtime exceptions! This is because this time, we have a typed array, that is an array containing the instances of a class which inherits from object—in other words any class in C#. On the other hand, what Array tells you is that it stores something in it, but it won’t (easily) reveal the type—it could be object, or int, or string, or anything else.


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *