Chorn Sokun's Weblog

Conquer inner fear, push it to the limit!

Archive for May 2011

LINQ 101 .NET Reflection

leave a comment »

In this post I am going over three points listed bellow:

What is .NET Reflection? Cut short it refer to a set of API built-in .NET Framework, which give you a greate power to load and manipulate type within assembly (.dll) one of the most favor use is to support late binding. There a whole lot of explaination available through google! but that all I care for now.

How about LINQ? stand for .NET Language-Integrated Query,

 a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language. The standard query operators allow queries to be applied to any IEnumerable<T>-based information source.

What it mean to me?
Assume that I had ITrap interface and a bunch of Trap implementation as show in the code bellow:

interface ITrap{
  void Setup();
  int OrderNr { get; };
}

class LevelOneTrap: ITrap{
  public void Setup(){
    Console.WriteLine("LevelOne Setup First");
  }
  public int OrderNr {
    get { return 1; }
  }
}

class LevelTwoTrap: ITrap{
  public void Setup(){
    Console.WriteLine("LevelTwo Setup Next");
  }
  public int OrderNr {
    get { return 2; }
  }
}

Now I want to Setup all trap by respecting it OrderNr which mean LevelOneTrap.Setup() must execute before LevelTwoTrap.Setup() so far so good? Let see how many lines of code needed:

var trapInterface = typeof(ITrap);

var trapImplementations = ( from t in trapInterface.Assembly.GetTypes()
                      where t.IsClass && t.GetInterfaces().Any(x => x == trapInterface)
                      select (ITrap)Activator.CreateInstance(t)
                  ).OrderBy(k=>k.OrderNr);

// time to play ;)
foreach( var trap in trapImplementations ) {
  trap.Setup();
}

//   LevelOne Setup First
//   LevelTwo Setup Next

Cool isn’t it? Life is short so our code!

Written by Chorn Sokun

May 7, 2011 at 12:39 pm

Posted in Programming, Tips & Tricks

Tagged with , ,