Is it possible to create an empty array without specifying the size?
For example, I created:
String[] a = new String[5];
Can we create the above string array without the size?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you are going to use a collection that you don’t know the size of in advance, there are better options than arrays.
Use a
List<string>instead – it will allow you to add as many items as you need and if you need to return an array, callToArray()on the variable.If you must create an empty array you can do this:
As of .NET 4.6, the following would be recommended for an empty array:
With C# 12/.NET8, there’s an even more succinct way (using collection expressions):