lunes, 8 de noviembre de 2010

Dynamic Objects

In the last few days, many people asked me about how to access to properties or methods marked as private or internal in order to do unit tests or consume libraries that they are not good defined (take care about this because if a method or property has been marked as internal maybe it is because the implementation of this method can change). Anyway, I will introduce a new interesing new feature en C#, the Dynamic Objects.


The Dynamic Objects are instances built in compilation time that grants full access to the private or internal properties of the instance. Its usage is very ease, you just have to define a class that extends to DynamicObject and use the keyword dynamic to instance it.





Pupil pupilWithPrivateGetScores = param;
dynamic pupil = new DynamicPupil(pupilWithPrivateGetScores);
String.Format("Scores= {0}", pupil.GetScores());

Where DynamicPupil inherits to DynamicObject:
using System.Dynamic;
using System.Linq;
using System.Xml.Linq;

namespace DynamicObject.Example
{
    public class DynamicPupil : DynamicObject
    {
        private Pupil element;
public DynamicElement(Pupil element)
        {
            this.element = element;
        }

        ...
}
}

Then, you will be able to use every method or property of that instance. Pay attention that the compilator will inform to you that there are errors because the dynamic type does not include the method that you are calling, but the compilator also will say to you this kind of types are build in compilation time, so you will be able to continue the compilation.

No hay comentarios:

Publicar un comentario