Best way to “push” into C# array

Course Queries Syllabus Queries 2 years ago

0 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Syllabus Queries related to Course Queries. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

Good day all

So I know that this is a fairly widely discussed issue, but I can't seem to find a definitive answer. I know that you can do what I am asking for using a List, but that won't solve my issue.

I teach a class in beginner C#. I have a PHP and Java Script background, and thus tend to think in terms of these languages.

I have been looking for the best com/tag/way">way to show my students how to com/tag/add">add elements to an array on the fly.We can't use Lists, as these are not part of the syllabus that I currently teach (although they do come in later in the semester).

I am thus looking for the simplest com/tag/way">way to perform a Java array.push(newValue) type scenario that will be understandable to novice coders without teaching them bad practice.

Here is how I have been approaching the problem so far:

for (int i = 0; i < myArray.Length; i++)
{
   if(myArray[i] == null)
   {
       myArray[i] = newValue;
       break;
   }
}

I just need to know if this is an acceptable approach, if I am teaching them any bad practices, or if there is a better / simpler com/tag/way">way of achieving my goal.

EDIT The crux of the matter is that the element needs to be com/tag/add">added into the first empty slot in an array, lie a Java push function would do.

Any advice would be greatly appreciated.

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.