Got C# to compile at Runtime but how to accept only certain types to be added to assembly

Hi I got compiling C# at runtime for my modding framework. Each class is represented as a string in a string array that is loaded from a text asset. I need to only allow certain types to be compiled. I got a CModdable class and I want to prevent compiling scripts that don’t inherit this or parent does not inherit it and so on. So basically I need to sandbox loading in code or people can’t change code that there are not suppose to.

        static Assembly CompileAssembly(string[] s)
        {
            var provider = new CSharpCodeProvider();
            var param = new CompilerParameters();

            //Add All of the Assembly refrences
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
                param.ReferencedAssemblies.Add(assembly.Location);

            //Generate a dll in memory
            param.GenerateExecutable = false;
            param.GenerateInMemory = true;

            //Compile
            var result = provider.CompileAssemblyFromSource(param,s);
            return result.CompiledAssembly;
        }

I don’t know if it’s possible to do that when compiling.

When you have an Assembly, you can load it into a separate AppDomain and inspect it with reflection before you decide to load it. Alternatively you can use Mono.Cecil to get a better look at the assembly.

1 Like

You can load it for reflection(there is a static function in Assembly class) and inspect the clases for the denied types

1 Like

It has been a while since I did this, but I recall it not working as expected for that purpose. I think that with ReflectionOnlyLoad, it wasn’t possible to resolve Types with dependencies from other Assemblies.

I had to make a new AppDomain specifically for reflection in order resolve all Types. Eventually I went with Mono.Cecil instead and it has turned out to be much better for inspecting assemblies.

1 Like

Thanks for the replies. I got it working with a work around, when getting a type from the assembly I check the type and only create a object of it if it meets the requirements. This takes up more memory but Mono.Cecil looks interesting.