Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coming from a C background, what's a good way to implement const reference data tables/structures in C#?

Tags:

c

c#

I'll give a quick example of what I'm familiar with implementing using C. The focus I think is on how the data can be used, not so much what I'm doing with it in the example :)

typedef struct  
{
  const char  *description;
  uint32_t    colour_id;      
  uint32_t    quantity;
} my_data_t;

const my_data_t ref_data[] =
{
  {"Brown Bear", 0x88,   10},
  {"Blue Horse", 0x666,  42},
  {"Purple Cat", 123456, 50},
};

void show_animals( void )
{
  my_data_t *ptr;

  ptr = &ref_data[2];

  console_write("Animal: %s, Colour: 0x%8X, Num: %d", 
      ptr->description,
      ptr->colour_id,
      ptr->quantity);
}

So I'm looking for advice on how similar data tables, or reference data, are implemented in C#. I'm getting the hang of the higher level side of things, but I haven't dealt with any table driven data methods yet.

As an example, what I might be trying to do in C# is to have a combo box allowing selection from the description field, while the colour id and quantity might be used to update read-only boxes.

That's a really simple example, but if I can determine a good way to implement that, I can extrapolate that to what I'm actually doing.

like image 639
Darcy Avatar asked Dec 11 '12 20:12

Darcy


1 Answers

I'd use a ReadOnlyCollection<T> of an immutable class.

public class MyData
{
    public MyData(string description, int colorId, int quantity)
    {
        Description = description;
        ColorId = colorId;
        Quantity = quantity;
    }
    public string Description {get; private set; }
    public int ColorId {get; private set; }
    public int Quantity {get; private set; }
}


...

public static readonly ReadOnlyCollection<MyData> refData =
    new ReadOnlyCollection<MyData>(
        new [] {
            new MyData("Brown Bear", 0x88,   10),
            new MyData("Blue Horse", 0x666,  42),
            new MyData("Purple Cat", 123456, 50)
            });
like image 80
Joe Avatar answered Oct 13 '22 00:10

Joe