In my previous article, we discussed about the concept of creating a dynamic class, using CodeDom namespace. Continuing along the same lines, we will discuss how we can add the methods to these classes. Thus, we will be using the same code, which we used in the previous discussion.
To add the method to the dynamic class, we will use CodeMemberMethod class, which provides different properties, which can be used to configure the definition of our methods. We will use this class to create a dynamic method, which will take two input parameters, perform their sum and return the value. Thus, we will create the basic method signatures. Hence, our code will look, as shown below-
- CodeTypeReference methodReturnType = new CodeTypeReference(typeof(System.Int32));
- CodeMemberMethod myMethod = new CodeMemberMethod();
- // Generate Method signatures.
- myMethod.Name = "MySum";
- myMethod.ReturnType = methodReturnType;
- myMethod.Attributes = MemberAttributes.Public;
Note the use of the CodeTypeReference class to specify the return type of our method. Next, we will use the CodeParameterDeclarationExpression class to create the parameters of our class and add them to the method. Thus, our code will look, as shown below-
- // Initialize for Method parameters
- CodeParameterDeclarationExpression methodPrm1 = new CodeParameterDeclarationExpression(typeof(Int32), "X");
- CodeParameterDeclarationExpression methodPrm2 = new CodeParameterDeclarationExpression(typeof(Int32), "Y");
- myMethod.Parameters.AddRange(new CodeParameterDeclarationExpression[] { methodPrm1, methodPrm2 });
Next, we will specify the method definition, using the CodeSnippetExpression class. Our method definition will simply return the sum of X and Y parameters. Thus, we will generate an expression to perform the sum of the two numbers and add it to the method. Thus, our code will look, as shown below-
- // Generate method definition
- CodeSnippetExpression codeSnippet = new CodeSnippetExpression("return X + Y");
- // Add method definition to method
- myMethod.Statements.Add(codeSnippet);
- // Add method to the class.
- cls.Members.Add(myMethod);
Our complete code will look, as given below-

Prasanna MuraliPosted Oct 9, 2016, 10:16 AM
Nice post..
Manoj KallaPosted Oct 7, 2016, 7:35 AM
Good one