Thursday, March 19, 2009

TypeForwardedTo (.NET)

We can use this class to move type from one assembly to another while not disrupting the callers compile against the original assembly .
Example : we have a source library (say lib.dll) which included lot of classes and we have use that class library for our application development. After some period of time the we refastening the source library (lib.dll) and it splits in to two source library to (say lib.dll and lib1.dll) .Then what happen to our application will it work? No because our application point to the lib.dll but some of the classes have move to lib1.dll to. So our application will generate error .To prevent this we can use “TypeForwardedTo”

Following 2 classes define in lib.dll
using System;
using System.Collections.Generic;
using System.Text;
namespace lib
{
public class car
{
public static void Do()
{
System.Console.WriteLine("car");

}
}
public class van
{
public static void Do()
{
System.Console.WriteLine("van");
}
}
}

Then the develop application using above lib.dll as following

using System;
using System.Collections.Generic;
using System.Text;
using lib;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
car.Do();
van.Do();
Console.ReadLine();

}
}
}

The Out put is :
car
van


Now we split above lib.dll to 2 dll to as following

lib.dll
using System;
using System.Collections.Generic;
using System.Text;
namespace lib
{
public class car
{
public static void Do()
{
System.Console.WriteLine("car");

}
}
}

lib1.dll
using System;
using System.Collections.Generic;
using System.Text;
namespace lib1
{
public class van
{
public static void Do()
{
System.Console.WriteLine("van");

}
}
}

Then replace the above lib.dll with new two dlls. Now what happen, the van class can’t find in new lib.dll so it generate and error.
So prevent such a error we ca use
“System.Runtime.CompilerServices.TypeForwardedTo” as following
Open the lib project and Open the AssemblyInfo.cs file and add the following line right after the assembly directives.

[assembly: TypeForwardedTo(typeof(lib1.van))]


now build projecj.
Now we have 2dlls, lib.dll and lib1.dll but we can still run oure previouse application without any error .....