James
James

Reputation: 1945

not able to call method inside dll

I have created dynamic dll using below code

var provider = new CSharpCodeProvider();
    var options = new CompilerParameters
    {
        OutputAssembly = Path.Combine(Path.GetTempPath(), "MyTestDll.dll")

    };

    string testsource = ""using System;" +
                                "namespace Myclass.GetNames" +
                                "{" +
                                "public class Test1 : IDisposable" +
                                "{" +
                                "public string GivemeNames(int No);" +
                                "}" +
                                "}";";

    provider.CompileAssemblyFromSource(options, new[] { testsource });

The dll is generated. But when i add this dll in my project, i cant reference method GivemeNames inside that dll. Do i need to add some more information while generating dll?

Upvotes: 0

Views: 88

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391664

The assembly won't contain the given class because the class cannot be compiled.

Specifically, here's the code you've got in that string, reformatted, but still identical to your code:

using System;
namespace Myclass.GetNames
{
    public class Test1 : IDisposable
    {
        public string GivemeNames(int No);
    }
}

The errors you should get from trying to compile this code would be:

  • 'Test1.GivemeNames(int)' must declare a body because it is not marked abstract, extern, or partial
  • 'Test1' does not implement interface member 'System.IDisposable.Dispose()'

So assuming the assembly was created, it certainly won't compile and contain that code.

You should try rewriting the code to this:

string testsource = @"
    using System;
    namespace Myclass.GetNames
    {
        public class Test1
        {
            public string GivemeNames(int No) { return ""Names: "" + No; }
        }
    }";

This will:

  1. Use @"..." syntax instead, which makes it easier to write strings over several lines, note the usage of double quotes in there.
  2. Drop IDisposable support until you're ready to add it (remember to add the Dispose method as well)
  3. Make sure the method returns something.

Upvotes: 1

Related Questions