Annotations...

So I've been mulling some ideas over after the whole abusing
lambdas for Hash table construction (here
and here) ... and after reading a post on Jb
Evain's blog
I decided to create a little bit of code for
doing annotations... so given a class say:

public class ClassA

{

    public int Id { get; set; }

    public string Name { get; set; }

}

You can then do this kind of thing (assuming you've added the
apropriate namespace where the Annotations static class
resides in)

[Test]

public void AnnotateClass()

{

    ClassA classA = new ClassA();

    classA.Annotate(IsValid => false);

    classA.Annotate(MapsToTable => "TblClassA",
Key => "Id");

    classA.Annotate(Roles => new []
{"Administrator", "User"});

   
Assert.IsFalse(classA.Annotation("IsValid"));

    Assert.AreEqual("TblClassA",
classA.Annotation("MapsToTable"));

    Assert.AreEqual("Id",
classA.Annotation("Key"));

}

Or, perhaps you want to attach some annotations to a
specific property... no problem!

[Test]

public void AnnotateProperty()

{

    ClassA classA = new ClassA();

    classA.Annotate(() => classA.Name,
CanBeNull => true);

    bool canBeNull =
classA.Annotation(() => classA.Name,
"CanBeNull");

    Assert.AreEqual(true, canBeNull);

}

Under the hood the values are stored against a dictionary where
the keys (in this case the instance of classA) are weak
referenced... so once classA is garbage collected the entries in
the dictionary will also dissapear in time (next time any method
touches the dictionary).

The nice thing is obviously you can directly interogate the
Annotations static class itself with a query expression to say
find all objects with a certain annotation.

Written on June 13, 2007