Skip to content

Hosting Samples

Oleg Shilo edited this page Jan 18, 2020 · 3 revisions

These are just a few code samples to illustrate the major use-cases.

The complete content of samples can be found here: https://github.com/oleg-shilo/cs-script.core/blob/master/src/CSScriptLib/src/CSScriptLib/samples.cs

public interface ICalc
{
    int Sum(int a, int b);
}
....
ICalc calc = CSScript.Evaluator
                     .LoadCode<ICalc>(@"using System;
                                        public class Script
                                        {
                                            public int Sum(int a, int b)
                                            {
                                                return a+b;
                                            }
                                        }");
int result = calc.Sum(1, 2);
dynamic script = CSScript.RoslynEvaluator
                         .LoadMethod(@"int Product(int a, int b)
                                       {
                                           return a * b;
                                       }");

int result = script.Product(3, 2);
public interface ICalc
{
    int Sum(int a, int b);
    int Div(int a, int b);
}
....
ICalc script = CSScript.RoslynEvaluator
                       .LoadMethod<ICalc>(@"public int Sum(int a, int b)
                                            {
                                                return a + b;
                                            }
                                            public int Div(int a, int b)
                                            {
                                                return a/b;
                                            }");
int result = script.Div(15, 3);
var log = CSScript.RoslynEvaluator
                  .CreateDelegate(@"void Log(string message)
                                    {
                                        Console.WriteLine(message);
                                    }");

log("Test message");
string code = @"using System;                            
                public class Script : ICalc
                {
                    public int Sum(int a, int b)
                    {
                        return a + b;
                    }
                }";

var script = CSScript.Evaluator.LoadCode<ICalc>(code);
int result = script.Sum(13, 2);
Clone this wiki locally