0

I have a global object array in my form. I wanna change the array length in several times. so I need to dispose it and new it with different length.

as below code from Do you need to dispose of objects and set them to null?

((IDisposable)obj).Dispose();

I have error:

Error 1 Cannot convert type 'business.person.clssHeadCustomer[]' to 'System.IDisposable' D:\acc2012\acc2012\WindowsFormsApplication1\hesabdari\frmCustomer.cs 80 14 presentation

now what should I do?!

Community
  • 1
  • 1
Iran_Girl
  • 439
  • 2
  • 11
  • 18

2 Answers2

1

In C#, there is a type of array called a List which doesn't need to have a fixed length

List<clssHeadCustomer> myList = new List<clssHeadCustomer>();

you can add and remove items from this freely

myList.Add(obj);
myList.Remove(obj);

Your error is saying that you can't cast your list to IDisposable because it (or its base classes) doesn't implement it so there is no valid conversion between the two types, an example implementation of IDisposable would start like

class MyClass : IDisposable
Sayse
  • 42,633
  • 14
  • 77
  • 146
  • the method return clssHeadCustomer is array. it means clssHeadCustomer is array. so what should I do for "myList.AddRange( cu.searchName(txtSearch));" ? – Iran_Girl Aug 14 '13 at 14:52
  • The shortcut would be add a `ToList()` to the end of it, `cu.SearchName...ToList()` – Sayse Aug 14 '13 at 14:54
0

In your example, you're getting that error because you're forcing an object that doesn't implement IDisposable to act as if it does and then trying to call its Dispose method. It doesn't have such a method so you can't call it.

If the objects in the array implement a Dispose method, then you should call them. You can also set array entries to null so the array doesn't have a reference to the objects. For example:

for (int i = 0; i < my_array.Length; i++)
{
    my_array[i].Dispose(); // Don't do this if the object's don't have Dispose.
    my_array[i] = null;
}

An array itself doesn't implement a Dispose method so you cannot call it for the array. You don't really need to anyway. The array itself is just a chunk of memory and doesn't really need disposing.

  • 1
    we know nothing about the `clssHeadCustomer` list so no idea if it implements `Dispose` or not. Even though the cast suggests that this classes dispose isn't being used, you can't distinctively say that no dispose method exists. I suspect OP has some experience in other languages where arrays do need to be disposed – Sayse Aug 11 '13 at 16:25