-1

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 programmatically now I want to create a hashtable so I am asking how?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Arunachalam
  • 5,417
  • 20
  • 52
  • 80

4 Answers4

5

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
  • 37,618
  • 18
  • 59
  • 69
1

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
  • 15,662
  • 5
  • 48
  • 74
1
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
  • 5,417
  • 20
  • 52
  • 80
0

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
  • 15,808
  • 23
  • 102
  • 173