Stupid Question 223: How do you do type forwarding in C#?
This is a continuation on Stupid Question 222: What is type forwarding in C#?
Continuing on the last blog post on what type forwarding is we will have a look at a basic implementation. I’ll keep the steps straight to the point without any extra code, just to make this example simple and the forwarding easy to understand.
A simple diagram explaining type forwarding
Let’s have a look at a basic implementation in 10 very easy steps
- Create a console app called TypeForwardExample
- Create a class library ClassLibraryY
- Create a class library ClassLibraryX
- Add to both a class of type TypeX
- Reference the Y library from the TypeForwardExample and use the TypeX and run the console app.
[sourcecode language=“csharp”]
using System;
using ClassLibraryY;
namespace TypeForwardExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new TypeX().Xstring);
Console.ReadLine();
}
}
}
[/sourcecode]
[sourcecode language=“csharp”]
namespace ClassLibraryY
{
public class TypeX
{
public string Xstring = “Hello " + Assembly.GetExecutingAssembly().CodeBase;
}
}
[/sourcecode]
It should output information from the Y library via the TypeX
6. Reference the X library from the Y library, and change namespace on X to Y
7. Remove the TypeX class in Y library
8. Add [assembly: TypeForwardedToAttribute(typeof(TypeX))] and use System.Runtime.CompilerServices & using ClassLibraryY
[sourcecode language=“csharp”]
using System.Runtime.CompilerServices;
using ClassLibraryY;
[assembly: TypeForwardedToAttribute(typeof(TypeX))]
namespace ClassLibraryY
{
//public class TypeX
//{
// public string Xstring = “Hello " + Assembly.GetExecutingAssembly().CodeBase;
//}
}
[/sourcecode]
- Unload the console application (right click unload) to be on the safe side and build the two libraries
- Move the DLL’s from LibraryY to the console applications folder where the executable is (the exe) and run the application. It should output information from the X library via the TypeX
Download the source code for the example above on type forwarding in C#
Comments
Last modified on 2013-07-25