Iris Classon
- CATALOG -
Iris Classon - In Love with Code
Stupid Question 223: How do you do type forwarding in C#?

[To celebrate my first year of programming I will ask a ‘stupid’ questions daily on my blog for a year, to make sure I learn at least 365 new things during my second year as a developer]

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

  1. Create a console app called TypeForwardExample
  2. Create a class library ClassLibraryY
  3. Create a class library ClassLibraryX
  4. Add to both a class of type TypeX
  5. 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]

  1. Unload the console application (right click unload) to be on the safe side and build the two libraries
  1. 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

Leave a comment (via email)


Last modified on 2013-07-25