Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/rafaelmelo007/csharpcodebuilder
Implemented c# source code class compiler in runtime using Microsoft.CodeAnalysis.
https://github.com/rafaelmelo007/csharpcodebuilder
code-analysis csharp dotnet-core6
Last synced: about 2 months ago
JSON representation
Implemented c# source code class compiler in runtime using Microsoft.CodeAnalysis.
- Host: GitHub
- URL: https://github.com/rafaelmelo007/csharpcodebuilder
- Owner: rafaelmelo007
- License: mit
- Created: 2022-02-12T12:59:54.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2022-02-12T14:13:24.000Z (almost 3 years ago)
- Last Synced: 2024-10-18T04:44:59.338Z (3 months ago)
- Topics: code-analysis, csharp, dotnet-core6
- Language: C#
- Homepage:
- Size: 11.7 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# CSharpCodeBuilder
c# helper to compile source code in runtime. Using Microsoft.CodeAnalysis.### Sample code
```c#
var sourceCode = @"using System;
public class ConsoleLogger : ILogger
{
public void Info(string msg)
{
Console.WriteLine($""[INFO] {msg}"", msg);
}
public void Warn(string msg)
{
Console.WriteLine($""[WARN] {msg}"", msg);
}
public DateTime Now()
{
return DateTime.Now;
}
}";// 1. Compile source code and generate its assembly
var scriptBuilder = new CSharpCodeBuilder();
var assembly = scriptBuilder.CompileCode(sourceCode, typeof(Console), typeof(ILogger), typeof(DateTime));// 2. Instantiate ConsoleLogger class
var consoleLogger = scriptBuilder.CreateInstance(assembly);
if (consoleLogger is null)
{
throw new Exception("Unable to create instance of ConsoleLogger.");
}// 3. Execute a method implemented in ConsoleLogger
var now = consoleLogger.Now();
consoleLogger.Info($"Print INFO at {now}!");
consoleLogger.Warn($"Print WARN at {now}!");// ****************************** //
public interface ILogger
{
void Info(string msg);
void Warn(string msg);
DateTime Now();
}```
### Output in console will be:
```shell
[INFO] Print INFO at 2/12/2022 11:02:42 AM!
[WARN] Print WARN at 2/12/2022 11:02:42 AM!
```