Click here to Skip to main content
16,011,988 members
Articles / Programming Languages / C#
Article

Using a Property to store an Array

Rate me:
Please Sign up or sign in to vote.
1.32/5 (16 votes)
19 May 20051 min read 97.9K   11   10
How to use a C# property to store and retrieve an array.

Introduction

I found I had a need to store simple arrays in properties for easy retrieval throughout an application such that they may be set in form A, displayed in form B or report A, further changed by form C and then viewed again in form A or form B or report A or report B. This is not the only solution to this problem (indexers, for example) but it suited me and, what I think makes it interesting, is that I could not find any documentation describing this method of using a property and an array anywhere.

Using the code

The code can be wrapped into a class similar to:

C#
using System;

namespace MyNamespace {
    /// <summary>
    /// Class to contain application properties.
    /// </summary>
    public class MyClass {
        public MyClass() {}

        /// <summary>
        /// Size of array.
        /// </summary>
        public const int Counter = 10;

        /// <summary>
        /// Widget: an array of widgets.
        /// </summary>
        private static int[] _widget = new int[Counter];
        public static int [] Widget {
            get { return _widget; }
            set { _widget = value; }
        }
    }
}

The property can be populated as follows...

C#
for (int <code>i</CODE> = 0; i <  MyClass.Counter; i++) {
    MyClass.Widget[i] = i;
}

... and retrieve and use the array as follows:

C#
double <code>_newWidget3</CODE> = MyClass.Widget[3];
double _newWidget5 = MyClass.Widget[5];
// and so on...

Points of interest

The property handles all of the indexing with no further intervention such that any array item inserted at point x can always be retrieved by referring to point x in the call. It also appears comfortable with a variety of data types such as int, string, object. Though I haven't tried every type, I see no reason for it not to work with other data types.

Widget properties are defined as static types. This is key to leveraging the power of using a property array across a variety of different objects (forms, reports, etc.) having differing scopes as well as having the ability to alter the values throughout the lifetime of the application with minimal effort.

I am amazed that I wasn't able to find examples of this since it is so simple. If you have seen other examples, please let me know. I spent some time researching this, however, that doesn't mean I didn't miss something (as we all do) so please set me straight (politely!).

License

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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralTechnically works, but is very ineffecient Pin
rvhughes24-Oct-07 8:46
rvhughes24-Oct-07 8:46 
GeneralRe: Technically works, but is very ineffecient Pin
_groo_10-Jul-08 23:04
_groo_10-Jul-08 23:04 
QuestionProperty as an array ... bounds check? Pin
GrahamLuks18-Oct-07 2:34
GrahamLuks18-Oct-07 2:34 
QuestionSetting a multi-dimensional array property??? Pin
knoljo12-Dec-06 13:10
knoljo12-Dec-06 13:10 
GeneralInteresting Pin
Marc Clifton19-May-05 8:52
mvaMarc Clifton19-May-05 8:52 
You bring up a complicated subject--how to share data across multiple code "domains", if you will. However...

I am amazed that I wasn't able to find examples of this since it is so simple.

Well, that's because one would really never do it this way. May I provide some, hopefully constructive, comments:

First off, by having MyClass.Widget be a static array, that means it can only be used for one type of usage. If, for example, I need to manage multiple sets of Widgets, this won't work.

You are returning the array itself, which doesn't bullet proof the usage. Instead of returning the class, provide a:

static int this[int index]
{
  get
  {
    // validate against "Counter"
    return widget[index];
  }
}


So that your class can catch inappropriate use. Then, the user can use it like int foo=MyClass[5];

But really, your still not really gaining anything beyond having a static array defined in the application's namespace that everyone can reference.

If you're using widget to store different "meanings" of that data at different indices, this isn't really a good idea either, because you lose all meaning of what the value at the index really, well, means. Instead, if each index is to mean something, then there should be an accompanying enumeration! So, the application indexes the array with an enumeration that has meaning and ensures that nobody makes a stupid typo that retrieves the wrong value.

For example:

public static int this[Enum e]
{
  get
  {
    // do your validation
    return _widget[Convert.ToInt32(e)];
  }
}


Now this is a bit more interesting. It's a "safe" indexing approach that is similar, but different, from a Hashtable. Now, if you get rid of your static properties and fields, and simply declare the class as a static, like:

namespace Foo
{
  public static MyClass myClass;
}


Then everyone can reference myClass. You can also have other instances, like "public static MyClass yourClass", and since the members and fields are non-static, yourClass and myClass will have different arrays!

So, those are some thoughts, while trying to keep it simple and stick to your original concept.

Marc

MyXaml
Advanced Unit Testing
YAPO
GeneralRe: Interesting Pin
legalAlien19-May-05 21:31
legalAlien19-May-05 21:31 
GeneralFxCop Pin
PaleyX19-May-05 7:05
PaleyX19-May-05 7:05 
GeneralRe: FxCop Pin
Ray Cassick19-May-05 14:43
Ray Cassick19-May-05 14:43 
GeneralRe: FxCop Pin
Anonymous20-May-05 19:26
Anonymous20-May-05 19:26 
GeneralRe: FxCop Pin
Anonymous21-May-05 3:08
Anonymous21-May-05 3:08 

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.