Pages

Friday, September 14, 2018

Type forwarding in .NET

Imaginary scenario:

Suppose you have a deployed application, console.exe for simplicity sake, and that console app depends on MathFactory.dll library, and for some reason you decided to move the class Calculations.cs to a new library. Now you need to re-compile the client application (console app), in some cases that comes at a cost, but .NET has already been shipped since its early days with a useful attribute, that can play a significant role in this scenario, where you don't need to compile the client application.


TypeForwardedToAttribute.



So in your console app, in Main method you have something similar to this:

public static void Main(string[] args)
        {
            MathFactory.Calculations calc =                                          new MathFactory.Calculations();
            int res = calc.Add(3, 4);
            Console.WriteLine(res);
            Console.ReadKey();
        }

Then you want to move the Calculations class from the MathFactory library to a new library, Calculator library for example.
all you need to do is:

  1. Move the class Calculations (with the same name and the same namespace) to the Calculator library
  2. Add this attribute to the AssemblyInfo.cs file of the MathFactory library (original library)[assembly: TypeForwardedTo(typeof(Calculations))]
  3. Now build both libraries (the console app will not compile off course because you moved the original class from the MathFactory library).
  4. Copy/paste the two DLLs (MathFactory.dll and Calculator.dll) from the MathFactory bin/debug folder, into the bin/debug folder of the console app, remember, you have added a reference to the Calculator library from the MathFactory library, in order to use the class Calculations in the TypeForwardedToAttribute.
  5. Run the console.exe from debug folder and you will find it's still functioning through the new Calculator library, and that's because the class Calculations is being forwarded to the new library from the original library.



Important Notes:
1. The original library shouldn't include the old code, comment it out or remove it.
2. The namespace and class name in the new library should be the same as the original library.




How to do code reviews correctly

Introduction Code review is a special event in the life cycle of software development, it's where ownership is transferred from the deve...