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();
}
}
}
Search
Generating class through C# code
LINQ to Lambda
As we know the LINQ is a language integrated query introduced in visual studio 2008 which offered an compact, and intelligible syntax for manipulating data & objects. Also Lambda expressions are introduced which is like an anonymous function that can be used to write local functions, delegates and expression tree. The below are few examples as how to modify the LINQ expression to Lambda.
Filtering
//Linq var column = from o in Orders where o.CustomersId = 45 select o; /* can be converted to Lambda as */ //Lambda var column = Orders.Where(o => o.CustomersId == 45);
Subscribe to:
Posts
(
Atom
)