Jul 252013
 
 July 25, 2013  Posted by at 4:52 pm Not So Stupid Questions  Add comments

[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

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]

9. Unload the console application (right click unload) to be on the safe side and build the two libraries

type forwarding

10. 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

type forwarding

Download the source code for the example above on type forwarding in C#

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

What is 7 + 10 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)