How can I save lines of C# code into a string?

Viewed 199

I'm writing a series of tests to validate code I'm writing. I want the documentation for the tests to list how the tests are finding errors. Instead of making sure the documentation gets updated with the tests I'd like to output the line of code. Is there a way to save it in a string?

The code would look like:

string Date = String.Format("Name = {0}, hours = {1:hh}", name, DateTime.Now);
string Code = ""Name = {0}, hours = {1:hh}", name, DateTime.Now"

Date would be evaluated, while Code would be the literal string. Something like:

string Date = string.Format(Code);
2 Answers

I think you should better use a Service to log it.But I'll still give you a solution. You can use the delegate to record the current state(It's a closure),and when sometime you need it , you can Invoke it and get its return value. Do it like this:

using System;
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var john = new Producer();
            var log = john.Produce();
            Console.WriteLine($"John's log is \"{log()}\"");
        }
    }

    class Producer
    {
        public Func<string> Produce()
        {
            var name = "John";
            Console.WriteLine("John is producing.");
            return () =>
            {
                return $"Name = {name}, hours = {DateTime.Now:hh}";
            };
        }
    }
}

Output:

John is producing.
John's log is "Name = John, hours = 08"

I believe that you might be able to use the new C# 9.0 code generators to do that. They allow you to do automated code rewriting such as injecting log calls which is similar to what your use case is.

Here is a cookbook with some "code rewriting" recipes:

https://github.com/dotnet/roslyn/blob/master/docs/features/source-generators.cookbook.md

I am new to code generators and they are still in preview(!) so I don't know if what you want is really possible but at least the general idea of inspecting the code and augmenting it on a per-line basis (in your case by making a string out of the code line as well as executing it) looks like what code rewriting generators could be used for.

Related