Type forwarding using TypeForwardedTo attribute in Runtime.CompilerServices
We used this feature to solve a problem internally and I was tempted to blog about this cool feature. Type forwarding allows you to move a type from one assembly to another without having to recompile the application that uses the original assembly.
Here is how this works:
Writing the original library (original.cs)
using System;
public class ClassToBeForwardedLater
{
public void SomeMethod()
{
Console.WriteLine("Inside ClassToBeForwardedLater in Original.dll");
}
}
Let us compile this to original.dll as below
csc /t:library original.cs
Building the application using the original assembly (application.exe)
using System;
class Application
{
public static void Main()
{
ClassToBeForwardedLater ctbf = new ClassToBeForwardedLater();
ctbf.SomeMethod();
}
}
Let us compile the executable as below
csc /r:original.dll application.cs
Let us run application.exe. You will get the following output
Inside ClassToBeForwardedLater in Original.dll
Re-implementing the original assembly in a new assembly (newlibrary.cs)
using System;
public class ClassToBeForwardedLater
{
public void SomeMethod()
{
Console.WriteLine("Inside ClassToBeForwarded in newlibrary");
}
}
Let us compile the newlibrary.dll as below
csc /t:library newlibrary.cs
Re-publish the original assembly, but this time with a type forwarded
using System;
using System.Runtime.CompilerServices;
[assembly:TypeForwardedTo(typeof(ClassToBeForwardedLater))]
Let us compile the original library as below
csc /t:library /r:newlibrary.dll original.cs
Let us run application.exe again and see what we get.
Inside ClassToBeForwardedLater in newlibrary
The method in the newlibrary is invoked though the application was built with a reference to original.dll. If you do ildasm on application.exe and view the metadata section you will see a reference to original.dll.