Click here to Skip to main content
13,251,398 members (55,778 online)
Click here to Skip to main content
Add your own
alternative version


24 bookmarked
Posted 18 Mar 2002

SparseArray for C#

, 18 Mar 2002
Rate this:
Please Sign up or sign in to vote.
A class that supports sparse arrays
<!-- Download Links --> <!-- Add the rest of your HTML here -->

I needed to store information in a grid similar to Excel where I did not want to restrain the user to a fixed multidimensional array that would be mostly unpopulated. Taking a page from NTFS, I decided to create a sparse array.

This array supports the bulk of those things that are supported by the System.Array class. Under the hood, it is using a hash table to store the elements with the index being the key.

Following is an example of how to use the SparseArray class.

// Create a 2 dimensional array
SparseArray array = new SparseArray(2);

// Set elements
array[3, 3] = "Hello";
array[9, 417] = "Nothing";

// Check bounds
int b;
b = array.GetLowerBound(0); // returns 0
b = array.GetLowerBound(1); // returns 0
b = array.GetUpperBound(0); // returns 9
b = array.GetUpperBound(1); // returns 417
b = array.Count; // returns 2

// Retrieve elements
object o = null;
o = array[3, 3]; // returns "Hello"
o = array[1, 1]; // returns null
o = array[9, 417]; // returns "Nothing"

// Walk the array elements
IEnumerator en = array.GetEnumerator();
while (en.MoveNext())
   o = en.Current;


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

David Hall
Chief Technology Officer
United States United States
I have been a Windows software developer since 1991. Most of what I create fills the need for some aspect of bigger projects that I consult on.

You may also be interested in...

Comments and Discussions

GeneralPerformance IndexToHash Pin
Siddhartha Hattangadi9-Jan-09 8:03
memberSiddhartha Hattangadi9-Jan-09 8:03 
Generallove it Pin
booglfucjk4-Dec-04 22:43
memberbooglfucjk4-Dec-04 22:43 
GeneralRe: love it Pin
booglfucjk4-Dec-04 23:38
memberbooglfucjk4-Dec-04 23:38 
GeneralThat's so cool! But... Pin
Yoonsoo Kim26-May-04 16:59
memberYoonsoo Kim26-May-04 16:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 19 Mar 2002
Article Copyright 2002 by David Hall
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid