tags:

views:

686

answers:

4

I want to generate code for creating a hash table object and assigning it with a key and a value programmatic . it should be similar to

Hashtable ht = new Hashtable();

ht.Add( "key1", "value1" );
ht.Add( "key2", "value2" );
ht.Add( "key3", "value3" );

for eg

CodeMemberMethod testMethod = new CodeMemberMethod();

        testMethod.Name = "Test" + mi.Name + "_" + intTestCaseCnt;
        testMethod.Attributes = MemberAttributes.Public;.....

here it creates a method programacticaly now i want to create a hashtable so i am asking how?

+5  A: 

For code generation consider the Text Template Transformation Toolkit (T4)

This template...

Hashtable ht = new Hashtable();
<#
    foreach (var obj in DataSource)
    {
#>
ht.Add( "<#= obj.Key #>", "<#= obj.Value #>" );
<#
    }
#>

...would generate this output...

Hashtable ht = new Hashtable();
ht.Add( "key1", "value1" );
ht.Add( "key2", "value2" );
ht.Add( "key3", "value3" );
...
ht.Add( "keyN", "valueN" );

Where N is the number of records in your DataSource.

The best thing is, this is built right into Visual Studio 2008

I have had good experiences with it

Andy McCluggage
dont want the entire tool just a piece of code in code dom
Arunachalam
Sorry if I misunderstood from you initial clear-as-mud question. The Edit isn’t much better either. I give up.
Andy McCluggage
Apologies, I missed the crucial part of the edit – “using codedom”. Shame this wasn’t there from the start and I could have saved some time.
Andy McCluggage
even with code dom this is a nice solution. Text transform is a pretty sweet tool.
Quibblesome
A: 

The two code generators I'm aware of are ...

Codesmith at ... main site, with a free version

T4 which is in Scott Hanselman has a blog post about it here

SteveC
+1  A: 

Where are you stuck? You know how to create a CodeMemberMethod, so you should be able to add statement objects to the CodeMemberMethod.Statements collection. You'll need one statement for the variable declaration, one for the assignment/initialization and one for each "Add"-Call.

BTW: I've used Code DOM in the past, but found that generating code directly with a templating engine is less works and makes the code far more readable. I usually use StringTemplate, and I'm very happy with it.

Niki
A: 
CodeParameterDeclarationExpression hashTableParam =new CodeParameterDeclarationExpression();
hashTableParam.Name = "hastable";

hashTableParam.Type = new CodeTypeReference(typeof(System.Collections.Hashtable));

this what i was looking for thanks for ur efforts

Arunachalam
You may want to also select this as the accepted answer
Quibblesome