Create a class with .NET Core and Roslyn

After my post first post on: Code Generation I decided to go a bit further, so today we’ll Create a class with .NET Core and Roslyn and write the output to the console.

Let’s see:

1. Create the application
2. Replace the contents of project.json
3. Replace the contents of Program.cs
4. Run the application

Get a copy of the code here:

Hope it helps

5 thoughts on “Create a class with .NET Core and Roslyn


    I am missing this function :

    public static Type CreateClass(params DynamicProperty[] properties);
    public static Type CreateClass(IEnumerable properties);
    From what I can see your example would allow me in .net Core to create a class, What I need is to create a class from off a Dictionary with Dynamic keys properties :

    var fieldProps = new Dictionary();
    fieldProps.Add(new System.Linq.Dynamic.Core.DynamicProperty(aggregate.Aggregate, typeof(object)), val);

    type = System.Linq.Expressions.DynamicExpression.CreateClass(fieldProps.Keys);
    var fieldObj = Activator.CreateInstance(type);
    foreach (var p in fieldProps.Keys)
    type.GetProperty(p.Name).SetValue(fieldObj, fieldProps[p], null);
    objProps.Add(new System.Linq.Dynamic.Core.DynamicProperty(group.Key, fieldObj.GetType()), fieldObj);

    Maybe there is a easier why to do what I want to do rather than using DynamicExpression

    Would you be able to put down such an example ?

    1. When you use the System.Linq.Expressions.DynamicExpression.CreateClass method you are creating Data classes which lives in an in-memory assembly in the current application domain. I´m not sure if you want to generate the c# code for the class, as I do in the provided code, or if you want to dynamically create and uses classes at runtime (out of the scope of this post).

      If you want to generate code, you just have to modify the signature of the CreateClass ( method to receive some parameters such as: Namespace, class name, IEnumerable< [Custom field descriptor type]>, etc… and then modify the body to use them and loop as necessary.

      Hope it helps!

  2. Hi, thanks for the example.
    I was wondering if there is way to have the using statements outside the namespace?
    using System;
    namespace CodeGenerationSample
    public class Order : BaseEntity, IHaveIdentity
    private bool canceled;
    public int Quantity

    public void MarkAsCanceled()
    canceled = true;

Leave a Reply