Generating class through C# code




namespace killercodes_in.CodeGeneration
{
public class GenerateClass
{
public void Generate()
{
//output file name
string fileName = "HelloWorld.cs";

//text writer to write the code
TextWriter tw = new StreamWriter(new FileStream(fileName, FileMode.Create));

//code generator and code provider
ICodeGenerator codeGenerator = new CSharpCodeProvider().CreateGenerator();
CSharpCodeProvider cdp = new CSharpCodeProvider();
codeGenerator = cdp.CreateGenerator();

//namespace and includes
CodeNamespace Samples = new CodeNamespace("Samples");
Samples.Imports.Add(new CodeNamespaceImport("System"));

//declare a class
CodeTypeDeclaration Class1 = new CodeTypeDeclaration("HelloWorld");
Samples.Types.Add(Class1);
Class1.IsClass = true;

//reference to a method - writeHelloWorld
CodeMethodReferenceExpression Method1Ref = new CodeMethodReferenceExpression();
Method1Ref.MethodName = "writeHelloWorld";
CodeMethodInvokeExpression mi1 = new CodeMethodInvokeExpression();
mi1.Method = Method1Ref;

//constructor for the class
CodeConstructor cc = new CodeConstructor();
cc.Attributes = MemberAttributes.Public;
cc.Statements.Add(mi1);
Class1.Members.Add(cc);

//method - writeHelloWorld
CodeMemberMethod Method1 = new CodeMemberMethod();
Method1.Name = "writeHelloWorld";
Method1.ReturnType = new CodeTypeReference(typeof(void));
//Method1.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "text"));
CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Hello World!!"));
Method1.Statements.Add(cs1);
Class1.Members.Add(Method1);

//method - Main
CodeEntryPointMethod Start = new CodeEntryPointMethod();
Start.Statements.Add(new CodeSnippetStatement("HelloWorld hw = new HelloWorld();"));
Class1.Members.Add(Start);

//generate the source code file
codeGenerator.GenerateCodeFromNamespace(Samples, tw, null);

//close the text writer
tw.Close();

RunClass sampleRun = new RunClass();
}
}
}