In this article, I am going to discuss the Advantages and Disadvantages of Arrays in C# with examples. This is one of the most frequently asked C# interview questions. Before proceeding to this article, I strongly recommended you read the following two articles.
The advantages of using an array in C# are as follows:
As the arrays are strongly typed so we are getting two advantages. First, the performance of the application will be much better because boxing and unboxing will not happen. Secondly, runtime errors will be prevented because of a type mismatch. In this case, at compile time it will give you the error if there is a type mismatch.
In the following example, we create an integer array with the name numberArray. As it is an integer array so we can store only the integer values within the array. As you can see when we try to store a string value within the array, immediately it gives us a compiler error saying “cannot implicitly convert a string to an integer“. This is the reason why we call the arrays in C# strongly typed.
You can get type mismatches and runtime errors with collection classes like ArrayList, Queue, Stack, etc which are present in the System.Collections namespace. We will discuss collections in detail in our upcoming articles. But in this article, to make you understand the type mismatch let us create an example using the ArrayList which is a collection in C#.
In the following example, we create one collection using the ArrayList collection class with the name numberArray. The collection classes that are present in the System.Collections namespace such as ArrayList is loosely typed. Loosely typed means, you can store any type of data in that collection. The ArrayList in C# is operated on object data type, which makes the ArrayList loosely typed. So, you will not get any compile-time error, but when you run the application, you will get a runtime error.
When you run the application, at runtime you will get the following exception. Here, it is trying to convert and store the string value into an integer variable and the casting is not valid, and hence it is throwing an exception saying that the Specified cast is not valid. If we use Array instead of ArrayList, then this kind of Exception will never get.
To overcome the above problems Collections are introduced in C#. And from the next and a few upcoming articles, we are going to discuss the Collection Framework in detail.
In the article, we are going to start Collections in C#. Here, in this article, I try to explain the Advantages and Disadvantages of Arrays in C# with examples. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.