0
public class Customer
{
    public int ProductId { get; set;},
    public string ProductName { get; set;},
    public string ProductDescription { get; set;},
    public float SalesAmount { get; set;}
}

public class Tracker<T>
{
    [Required, ValidateObject]
    public T Body { get; set; }
    public Date date { get; set; }
    public string GUID{ get; set; }
}

Is there a way to create a class, automatically by periods or concatenating string, which will auto compile in Visual Studio

public class CustomerTracker : Tracker<Customer>
{
}

So instead of creating 100s of class as above, I can take any class and it will generate this class automatically. Does any C# Library function permit this?

so Customer.Tracker = public class CustomerTracker : Tracker<Customer>
Customer.ListTracker = public class CustomerTracker : Tracker<IEnumerable<Customer>>

or Food.Tracker = public class FoodTracker : Tracker<Food>

  • 1
    what do you mean by creating class? you havent created classes, you have just declared classes. New() or Activator.CreateInstance() create an instance of class .. Could you precise what you want, its not very clear... – Frenchy Sep 23 '19 at 06:38
  • hi @Frenchy I would to be able to dynamically create classes by writing this Customer.Tracker, and have the C# compiler automatically know what it means, instead of going through 1000s of our classes, and manually declaring classes, –  Sep 23 '19 at 06:42
  • It would be better to describe the problem you want to solve. – mtkachenko Sep 23 '19 at 06:47
  • Anything you do with reflection will need the code to be loaded into a runtime, so the compiler will not be able to automatically know what it means. Code templating systems might be more useful to you. So basically they generate the class files for you based on your short forms. This then can be used in your project and compiler will know about the classes.Have a look at the link: https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/how-to-create-a-class-using-codedom – peeyush singh Sep 23 '19 at 06:47
  • hi @mtkachenko we have to declare 1000s of classes which wrap the class with a tracker, instead of creating a 1000 classes manually, I would like to have a wrapper function which is readable in own way –  Sep 23 '19 at 06:49
  • @DerrikRodgers `Why` do you need to declare 1000s classes? – mtkachenko Sep 23 '19 at 06:53
  • hi @mtkachenko we have functional areas, customers, employees, food, sales, purchase, inventory, etc –  Sep 23 '19 at 06:57
  • @DerrikRodgers If you have to implement the approach described in the question (dynamically creation of 1000s classes) most likely you use wrong approach. That's why I asked why you want this. Describe your original problem in the question and the reason you want to create tons of classes. – mtkachenko Sep 23 '19 at 07:03
  • hi @mtkachenko feel see this question which addresses more of architectural pattern, https://stackoverflow.com/questions/58055741/net-core-wrap-dto-in-response-pattern-in-dynamic-variable-way, thanks –  Sep 23 '19 at 07:04

2 Answers2

0

if you want to create coding dynamically and compile dynamically you could do that like in my math program, to dynamically add some functions without need to recompile the project..

i have text file with body of program:

using System;

// file curve.txt
namespace UserFunction
{                
    public class BinaryFunction
    {
        public static double MyFunction(double x, double param)
        {
            return param == 0 ?  MyFunction0(x, 0.3) : MyFunction1(x);
        }

        private static double MyFunction0(double x, double param)
        {
            return (1 - param) * x + param * (Math.Pow(x, 3));
        }
        private static double MyFunction1(double x)
        {
            return x * 2;
        }
    }
};

And in project C#, i dynamically compile the program and create dll. After i can call the method from dll created.

            // in project C#
    private Func<double, double, double> betterFunction;

    private MethodInfo CreateAndCompileFunction(string filename)
    {
        FileInfo fi = new FileInfo(@".\folder\CurveAssembly.dll");
        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerParameters compilerparams = new CompilerParameters();
        compilerparams.OutputAssembly = @".\folder\CurveAssembly.dll";
        CompilerResults results = provider.CompileAssemblyFromFile(compilerparams, filename);

        if (results.Errors.Count > 0)
        {
            // Display compilation errors.
            Console.WriteLine("Errors building {0} into {1}",
                fi.FullName, results.PathToAssembly);
            foreach (CompilerError ce in results.Errors)
            {
                Console.WriteLine("  {0}", ce.ToString());
            }
        }
        else
        {
            // Display a successful compilation message.
            Console.WriteLine("Source {0} built into {1} successfully.",
                fi.FullName, results.PathToAssembly);
        }

        Type binaryFunction = results.CompiledAssembly.GetType("UserFunction.BinaryFunction");
        return binaryFunction.GetMethod("MyFunction");
    }
    public void compileFunction(string curvename)
    {
        MethodInfo function = CreateAndCompileFunction(@".\folder\curve.txt");
        betterFunction = (Func<double, double, double>)Delegate.CreateDelegate(typeof(Func<double, double, double>), function);
    }


    //calling the method inside the dll (betterfunction)
    public double MyFunction(double x, double param)
    {
        return betterFunction(x, param);
    }
Frenchy
  • 16,386
  • 3
  • 16
  • 39
  • hi Frenchy, thanks I will have to investigate how to use for classes above, apprecate it –  Sep 23 '19 at 07:17
  • T4 templates are kinda similar to this functionality. Depending it may be worth investigating: https://learn.microsoft.com/en-us/visualstudio/modeling/code-generation-and-t4-text-templates?view=vs-2019 – Svend Sep 23 '19 at 07:41
  • gave points and accepted answer, feel free to thumbs up question also, thanks –  Sep 23 '19 at 15:04
0

It looks like you need many response classes without implementation to make your public API nice. I.e. instead of return BaseResponse<SomeClass> you want to return SomeClassResponse : BaseResponse<SomeClass>. If so I would recommend to use T4 templates. Using T4 you can write template logic like this:

  1. get all classes from YourApp.Domain namespace
  2. for each domain class generate response classes like public sealed SomeClassresponse : BaseResponse<SomeClass> {}
  3. just use these classes in your code because they are known in compile time.

You don't need to generate classes in runtime because you already know all classes you need to generate. Also anyway runtime generation will be slower than T4 generation.

mtkachenko
  • 5,389
  • 9
  • 38
  • 68