views:

132

answers:

4

A particular class has a Hashtable containing 1..N elements. I'm wondering if there are generic getter/setter methods for the Hashtable used in a class. I'm looking to make the hashtable values behave more like regular object properties:

public class foo 
{
  private HashTable _stuff;
  public HashTable stuff { get; set; }
  public foo() {}
}

I was wondering if something like this can happen:

foo bar = new foo();
bar.stuff.name; //returns the data in the 'name' index if it exists
bar.stuff.name = "Me"; //sets the stuff[name] value = "me"
A: 

You can't do this with C#, at least not in the current version. What you'd need is the equivalent of method_missing in ruby.

If this was C# 4.0 you could do something similar to this with anonymous types and the dynamic keyword, however you'd need to know the keys up front.

jonnii
+1  A: 

There's nothing like that in the current version of C#. The dynamic stuff in C# 4.0 will make this easier.

In the meantime, why not just make Name (and other values) simple properties? While you're at it, you'll find the generic Dictionary<K,V> easier to work with than HashTable.

Michael Petrotta
The elements in the Hash are coming from a database query. The keys in the hash == db columns from the query. We were hoping that a change to the stored procedure would change a dynamically generated HTML table/list on the front end without a bunch of extra coding to account for the added field.
JayTee
For that, a standard table/dictionary seems like the easiest way to go. For each key in the table, add a column to the generated HTML table.
Michael Petrotta
A: 

Apparently you can do that in .NET 4.0 by implementing the IDynamicMetaObjectProvider interface... doesn't seem trivial though !

Thomas Levesque
A: 

Depending on how you are rendering the HTML there might be a few ways to solve your problem. The code above is as noted not possible at current in c#.

First of all I assume there's a reason why you don't use ADO objects, that usually solve the rendering problems you mention (together with GridView or similar).

If you want to generate a class with "dynamic" properties you can create a [propertybag][1]

[1]: http://www.codeproject.com/KB/recipes/propertybag.aspx it will not make the above code possible though but will work with a rendering engine based on TypeDescriptor using custom descriptors.

Rune FS