Sunday, November 2, 2008

Array Usage

Arrays vs. Collections
Class library designers might need to make difficult decisions about when to use an array and when to return a collection. Although these types have similar usage models, they have different performance characteristics. You should use a collection in the following situations:
1. When Add, Remove, or other methods for manipulating the collection are supported.
2. To add read-only wrappers around internal arrays.


Using Indexed Properties in Collections
You should use an indexed property only as a default member of a collection class or interface. Do not create families of functions in non-collection types. A pattern of methods, such as Add, Item, and Count, signal that the type should be a collection.



Array Valued Properties
You should use collections to avoid code inefficiencies. In the following code example, each call to the myObj property creates a copy of the array. As a result, 2n+1 copies of the array will be created in the following loop.
Visual Basic
Dim i As Int32
For i = 0 To obj.myObj.Count - 1
DoSomething(obj.myObj(i))
Next i
C#
for (int i = 0; i < obj.myObj.Count; i++)
DoSomething(obj.myObj[i]);


Returning Empty Arrays
String and Array properties should never return a null reference. Null can be difficult to understand in this context. For example, a user might assume that the following code will work.
Visual Basic
Public Sub DoSomething()
Dim s As String = SomeOtherFunc()
If s.Length > 0 Then
' Do something else.
End If
End Sub
C#
public void DoSomething()
{
string s = SomeOtherFunc();
if (s.Length > 0)
{
// Do something else.
}
}
The general rule is that null, empty string (""), and empty (0 item) arrays should be treated the same way. Return an empty array instead of a null reference.

No comments: