Wednesday, January 25, 2017

Dynamic methods in C# using CodeDom

In my previous article, we discussed how we can create a dynamic class using CodeDom namespace. Now we will discuss how we can add methods to these classes. For this we will be use the same code as in our previous discussion.
For adding method to the class, we will use CodeMemberMethod class, which provides different properties, to define methods. For our sample we will create a dynamic method which will take two input parameters, calculate their sum and return the sum. Let's with basic method signatures. So our code will look like the following: 
  1. CodeTypeReference methodReturnType = new CodeTypeReference(typeof(System.Int32)); 
  2. CodeMemberMethod myMethod = new CodeMemberMethod();  
  3.   
  4.  // Generate Method signatures.  
  5.  myMethod.Name = "MySum";  
  6.  myMethod.ReturnType = methodReturnType;  
  7.  myMethod.Attributes = MemberAttributes.Public;  
We use of the CodeTypeReference class to specify the return type of our method. To add parameters for this method, we will use the CodeParameterDeclarationExpression class. So our code will look like the following: 
  1. // Initialize for Method parameters  
  2. CodeParameterDeclarationExpression methodPrm1 = new CodeParameterDeclarationExpression(typeof(Int32), "X");  
  3. CodeParameterDeclarationExpression methodPrm2 = new CodeParameterDeclarationExpression(typeof(Int32), "Y");  
  4. myMethod.Parameters.AddRange(new CodeParameterDeclarationExpression[] { methodPrm1, methodPrm2 });  
Next, to specify the method definition we use the CodeSnippetExpression class. Our method will simply the sum of our input parameters. So we will generate an expression to perform the sum of the numbers and add it to the method. So our code will change to the following: 
  1. // Generate method definition  
  2. CodeSnippetExpression codeSnippet = new CodeSnippetExpression("return X + Y");  
  3.   
  4. // Add method definition to method  
  5. myMethod.Statements.Add(codeSnippet);  
Finally we add the method to our class definition using following code: 
  1. // Add method to the class.  
  2. cls.Members.Add(myMethod);  
So our complete code will look like the following: 
  1.  CodeNamespace nameSpace = new CodeNamespace("sampleNameSpace");  
  2.   
  3.  nameSpace.Imports.Add(new CodeNamespaceImport("System"));  
  4.  nameSpace.Imports.Add(new CodeNamespaceImport("System.Linq"));  
  5.  nameSpace.Imports.Add(new CodeNamespaceImport("System.Text"));  
  6.   
  7.  CodeTypeDeclaration cls = new CodeTypeDeclaration();  
  8.  cls.Name = "SampleClass";  
  9.  cls.IsClass = true;  
  10.  cls.Attributes = MemberAttributes.Public;  
  11.  nameSpace.Types.Add(cls);  
  12.   
  13.  // Initialize for Method Return type  
  14.  CodeTypeReference methodReturnType = new CodeTypeReference(typeof(System.Int32));  
  15.  CodeMemberMethod myMethod = new CodeMemberMethod();  
  16.   
  17.  // Generate Method signatures.  
  18.  myMethod.Name = "MySum";  
  19.  myMethod.ReturnType = methodReturnType;  
  20.  myMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;  
  21.   
  22.  // Initialize for Method parameters  
  23.  CodeParameterDeclarationExpression methodPrm1 = new CodeParameterDeclarationExpression(typeof(Int32), "X");  
  24.  CodeParameterDeclarationExpression methodPrm2 = new CodeParameterDeclarationExpression(typeof(Int32), "Y");  
  25.  myMethod.Parameters.AddRange(new CodeParameterDeclarationExpression[] { methodPrm1, methodPrm2 });  
  26.   
  27.  // Generate method definition  
  28.  CodeSnippetExpression codeSnippet = new  CodeSnippetExpression("return X + Y");  
  29.   
  30. // Add method definition to method  
  31.  myMethod.Statements.Add(codeSnippet);  
  32.   
  33.  // Add method to the class.  
  34.  cls.Members.Add(myMethod);  
  35.   
  36.  CodeCompileUnit compileUnit = new CodeCompileUnit();  
  37.  compileUnit.Namespaces.Add(nameSpace);  
  38.  CSharpCodeProvider csharpcodeprovider = new CSharpCodeProvider();  
  39.   
  40.  CSharpCodeProvider provider = new CSharpCodeProvider();  
  41.   
  42.  using (StreamWriter sw = new StreamWriter(@"C:\TestFile.cs"false))  
  43.  {  
  44.      IndentedTextWriter tw = new IndentedTextWriter(sw, "    ");  
  45.      provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions());  
  46.      tw.Close();  
  47.  }  
Run the application and see the code getting generated: 
  1. //------------------------------------------------------------------------------  
  2. // <auto-generated>  
  3. //     This code was generated by a tool.  
  4. //     Runtime Version:4.0.30319.42000  
  5. //  
  6. //     Changes to this file may cause incorrect behavior and will be lost if  
  7. //     the code is regenerated.  
  8. // </auto-generated>  
  9. //------------------------------------------------------------------------------  
  10.   
  11. namespace sampleNameSpace {  
  12.     using System;  
  13.     using System.Linq;  
  14.     using System.Text;  
  15.       
  16.       
  17.     public class SampleClass {  
  18.           
  19.         public int MySum(int X, int Y) {  
  20.             return X + Y;  
  21.         }  
  22.     }  
  23. }  
So this was about how we can generate the dynamic class and add methods to it. Hope you enjoyed reading it. Happy coding...!!!

No comments:

Post a Comment