I have a class (HelloWorld.cs):
public partial class HelloWorld
{
public void SayHello()
{
var message = "Hello, World!";
var length = message.Length;
Console.WriteLine("{1} {0}", message, length);
}
}
The above class the property BuildAction = Compile.
I have another class in a separate file (HelloWorldExtend.cs):
public partial class HelloWorld
{
public void SayHelloExtend()
{
var message = "Hello, World Extended!";
var length = message.Length;
Console.WriteLine("{1} {0}", message, length);
}
}
But the properties of the class are: BuildAction = None and Copy to output directory = Copy if newer
Now the main method: Its using Roslyn.
static void Main(string[] args)
{
var code = File.ReadAllText("HelloWorldExtend.cs");
var tree = SyntaxFactory.ParseSyntaxTree(code);
var compilation = CreateCompilation(tree);
var model = compilation.GetSemanticModel(tree);
ExecuteCode(compilation);
Console.ReadLine();
}
private static void ExecuteCode(CSharpCompilation compilation)
{
using (var stream = new MemoryStream())
{
compilation.Emit(stream);
var assembly = Assembly.Load(stream.GetBuffer());
var type = assembly.GetType("HelloWorld");
var greeter = Activator.CreateInstance(type);
var methodextend = type.GetMethod("SayHelloExtend");
methodextend.Invoke(HelloWorld, null);
//Works perfect
var method = type.GetMethod("SayHello");
method.Invoke(greeter, null);
//method is returned null and gives an error : {"Object reference
not set to an instance of an object."}
}
}
IS it possible to use roslyn to give the same effect as a regular partial class to an existing class where one class is compiled during build and another is compiled at runtime in the same assembly.