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:
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:
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:
So our complete code will look like the following:
Run the application and see the code getting generated: