How do I find the length of an array without using the Length property in C#?
views:
137answers:
4
+1
A:
You can use Length Property right? If you are using Linq Name space you can use Count() extension method also.
Anuraj
2010-01-11 05:45:02
A:
Iterate though it using a counter and catch when you get indexoutofbounds exception, but why.
rerun
2010-01-11 05:47:50
+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
2010-01-11 05:51:24
i like this any other way possible for this
ratty
2010-01-11 06:08:44
+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
2010-01-17 21:39:18