Type forwarding is a powerful feature in the Common Language Runtime which allows to move a type from one assembly to another, without re-compiling the consumer application of the assembly.
Lets say we have a application that uses a class named About, which is in the referenced library named Utility.dll. Company decided to update the Utility library and wanted to move the About class to a separate library named Profile.dll. After releasing the new libraries (Utility.dll and Profile.dll) old version of the application will give an error, because it can not find the About class in the Utility library. We can overcome this situation using Type forwarding.
Lets code the above example.
Original About class in the Utility library
namespace Utility
{
public class About
{
public string GetInfo()
{
return "About class in the Utility.dll";
}
}
}
Application that uses the Utility library
namespace TestApp
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Utility.About about = new Utility.About();
MessageBox.Show(about.GetInfo());
}
}
}
When we click the button we will get the message box with the message "About class in the Utility.dll".
Move the About class to new library named Profile. (We can drag and drop the About class if the libraries are in the same solution. anyway after moving, Utility does not have the About class any more and Profile has it).
namespace Utility
{
public class About
{
public string GetInfo()
{
return "About class in the Profile.dll";
}
}
}
Now the About class is with the Profile library and the namespace should be Profile. But in order to use the type forwarding we must keep the namespace as Utility (as the old namespace).
Next step is to reference the Profile library into the Utility library and add the following attribute to AssemblyInfo.cs of the Utility library.
[assembly: TypeForwardedTo(typeof(About))]
Make sure that following using statement are there also.
using System.Runtime.CompilerServices;
using Utility;(This is because still the namespace of the About class is Utility)
Now re-compile the Utility library. This will automatically compile the Profile library because it is referenced by Utility library. Copy both the dlls (Utility.dll and Profile.dll) to the location where you have the application exe and run the application.
Now when we click the button we will get the message box with the message "About class in the Profile.dll".
Finally, this is a great feature that will improve the maintainability of our application.