Reputation: 50
This is my code, but clear
method is not working, but I can't find the error.
This is the first time that clear method it's not working, anyone can help me?
using System;
using System.Collections.Generic;
public class test{
public static void Main()
{
try {
int[] myArr = {-1, 4, 8, 6};
PrintIndexAndValues(myArr);
Console.WriteLine();
Console.WriteLine("Taking index out of bound:");
Array.clear(myArr, 1, 2);
Console.WriteLine("Array After Operation:");
PrintIndexAndValues(myArr);
}
}
public static void PrintIndexAndValues(int[] myArr)
{
for (int i = 0; i < myArr.Length; i++) {
Console.WriteLine("{0}", myArr[i]);
}
}
}
Upvotes: 2
Views: 627
Reputation: 117
From Arrays (C# Programming Guide):
The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance.
If you want to be able to use Clear() the way you inted to, you should use a List instead:
List<int> myList = new List<int>{-1, 4, 8, 6};
// Do some stuff with your list
myList.Clear();
Edit: Your PrintIndexAndValues actually only prints the values, here's how you could do it instead:
public static void PrintIndexAndValues(List<int> myList)
for (int i = 0; i < myList.Count; i++)
{
Console.WriteLine("{0}: {1}", i, myList[i]);
}
Edit2: Just realized that you probably wanted to remove the first and last element of the array, not clear the whole array? This should do the trick:
myList.RemoveAt(3)
myList.RemoveAt(0)
Upvotes: 2
Reputation: 81
The following is your corrected code
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
int[] myArr = {-1, 4, 8, 6};
PrintIndexAndValues(myArr);
Console.WriteLine();
Console.WriteLine("Taking index out of bound:");
Array.Clear(myArr, 0, myArr.Length);
Console.WriteLine("Array After Operation:");
PrintIndexAndValues(myArr);
}
public static void PrintIndexAndValues(int[] myArr)
{
for (int i = 0; i < myArr.Length; i++)
Console.WriteLine("{0}", myArr[i]);
}
}
This will set ALL values in your array to 0.
Upvotes: 0