tags:

views:

137

answers:

4

How do I find the length of an array without using the Length property in C#?

+1  A: 

You can use Length Property right? If you are using Linq Name space you can use Count() extension method also.

Anuraj
A: 

Iterate though it using a counter and catch when you get indexoutofbounds exception, but why.

rerun
+1  A: 

Use the foreach construct to iterate through each item in the array, incrementing a counter for each iteration.

Something like this:

object[] o_arr = new object[5];

// code to initialise array

int i = 0;
foreach(object o in o_arr)
{
    i++;
}

Console.WriteLine(i);
Shoko
i like this any other way possible for this
ratty
+1  A: 

Here's a "different" solution. :)

Usage:

byte[] data = new byte[100];
int length = GetLength(data);

Implementation:

private static int GetLength(Array array)
{
    if (array == null)
        throw new ArgumentNullException("array");
    if (!array.GetType().FullName.EndsWith("[]"))
        throw new ArgumentException("'array' must be an szarray.");

    GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned);
    try
    {
        IntPtr ptr = handle.AddrOfPinnedObject();
        int offsetToArrayLength = -8;
        int length = (int)Marshal.PtrToStructure(new IntPtr(ptr.ToInt64() + offsetToArrayLength), typeof(int));
        return length;
    }
    finally
    {
        handle.Free();
    }
}
280Z28