Search code examples
c#namespacesruntime-compilation

C# Runtime Compilation - Add new interface to namespace


I am currently confused, if it is possible to compile an interface at runtime and add it to a "hardcoded" namespace.

Some code to explain:

using System;
using System.Runtime.CompilerServices;
using EngineCore;

namespace EngineCore
{
    public interface iMobilePhones
    {
        string phoneNumber {get; set;}
        string phoneRingtone {get; set;}

        void CallNumber(string phoneNumber);
    }
}

This is the runtime compiled interface, I want to add to the EngineCore namespace at runtime.

The compilation seems to work as expected and as you can see I compiled it using the EngineCore namespace.

using System;
using System.Runtime.CompilerServices;
using EngineCore;

namespace EngineCore
{
    public class EQMobilePhoneCheap : iMobilePhones
    {
        //iMobilePhones interface members
        private string PhoneNumber;
        private string PhoneRingtone = "Default";

        public string phoneNumber
        {
            get
            {
                return PhoneNumber;
            }
            set
            {
                PhoneNumber = value;
            }
        }
        public string phoneRingtone
        {
            get
            {
                return PhoneRingtone;
            }
            set
            {
                PhoneRingtone = value;
            }
        }

        //iMobilePhones interface functions
        public void CallNumber(string phoneNumber)
        {

        }

    }
}

This is the second runtime compiled code. As you can see, I am trying to use the iMobilePhones interface I compiled before.

But the compilation fails because iMobilePhones is not an interface of EngineCore

The actual question:

So I am wondering if there is a way to "register" the previously compiled interface iMobilePhones to the EngineCore namespace?

Thank you very much for reading. Any suggestions are welcome.


Solution

  • You simply need to add a reference to the assembly containing the interface when you compile code that uses it.