Thursday, June 14, 2007

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<bool>("IsValid"));
    Assert.AreEqual("TblClassA", classA.Annotation<string>("MapsToTable"));
    Assert.AreEqual("Id", classA.Annotation<string>("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<bool>(() => 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.

 |  | 
posted @ Wednesday, June 13, 2007 10:32:16 PM (New Zealand Standard Time, UTC+12:00)    Comments [2] | Trackback | Tracked by:
"Getting your DSL on..." (Bitter Coder) [Trackback]
"mucking about with hashes..." (Bitter Coder) [Trackback]
Thursday, June 14, 2007 1:33:25 AM (New Zealand Standard Time, UTC+12:00)
Very nice! Can you make the source code available? Thanks!
Rob
Thursday, June 14, 2007 1:52:02 AM (New Zealand Standard Time, UTC+12:00)
I will do, just going to tidy it up a bit first.
Comments are closed.
Search
FeedCount

Tags...
Who am I?
Alex Henderson
Alex Henderson
Auckland, New Zealand
Managing Director at Dev|Defined Limited

"Self Confessed Coding Junky for 15 years"
View Alex Henderson's profile on LinkedIn
 
Mobile: +64-21-402-969
Email: bittercoder 'at' gmail 'dot' com
MSN: bittercoder_nz@hotmail
Skype: alex.devdefined
Navigation