Static Reflection in .NET

LINQ expressions have proven to be extremely versatile, popping up in all sorts of areas. “Static Reflection” seem to be the latest hype. But what is static reflection anyway, and why is it good or why is it bad?

Reflection is used to obtain information about the code you are executing, and to use that information to interact with the code dynamically. Sometimes reflection is used to interact dynamically with code that is statically known by a program already. For example, data binding heavily relies on reflection to dynamically read and write properties. The calling program knows about those properties statically, but the data binding libraries do not. In data binding, object properties are often identified by their name, expressed as a string. That string is then used by the libraries to construct a PropertyInfo object.

Time for an example. Given this class:

public class Example
{
    public string Description { get; set; }
}


You can obtain a PropertyInfo object describing the Description property as follows:

PropertyInfo pi = typeof(Example).GetProperty("Description");


We may have an issue here. If I make a typing mistake in the GetProperty call, I don’t get a compiler error. At runtime, the call will return null, probably leading to a NullReferenceException down the road. And of course, Visual Studio Intellisense will not help me to type it right. Also, if I rename the property, for example to “Summary”, the GetProperty call will be broken, without a compile-time error. Static Reflection is one technique to avoid these issues.

Using LINQ expressions, we could create an API that allows us to do something like the following:

PropertyInfo pi = StaticReflector.GetProperty(Example e => e.Description);


The downside of this approach is that it doesn’t work with anonymous types. So I propose a different mechanism. What we need is something that statically gives us access to a type. Any generic interface will do. I propose the following:

public interface IStaticReflector<T>
{
}


Given this interface, we can define a series of extension methods, for example:

public static class StaticReflectorExtensions
{
    public static PropertyInfo PropertyInfo<T, U>(this IStaticReflector<T> obj, Expression<Func<T, U>> selector)
    {
        var body = selector.Body as MemberExpression;
        return body.Member as PropertyInfo;
    }
}


Notice how the obj parameter is not really used in the PropertyInfo method. It does serve a purpose however: it allows us to use type inference on the type T, and I get full Intellisense. For example:

IStaticReflector<Example> reflector = null;
PropertyInfo pi = reflector.PropertyInfo(e => e.Description);


Granted, initializing a variable to null and then calling a method on it is a bit weird. We need a more elegant way to create these things:

public static class StaticReflector
{
    public static IStaticReflector<T> Create<T>()
    {
        return null;
    }
}


Now we can write:

PropertyInfo pi = StaticReflector.Create<Example>().PropertyInfo(e => e.Description);


This still doesn’t work on anonymous types though. For those, we could use the following:

public static class ObjectExtensions
{
    public static IStaticReflector<T> GetReflector<T>(this T obj)
    {
        return null;
    }
}


Now we can write things such as:

var anonymous = new { Description = "Example" };

PropertyInfo pi = anonymous.GetReflector().PropertyInfo(e => e.Description);


I do prefer the StaticReflector.Create<T>() method is case the type name is known though.

Are we done? Not really. Let’s go back to dynamic reflection using string names. Lot’s of things could go wrong there, and we don’t get any warnings. The situation has not gone worse, but still lot’s of things can go wrong. So the PropertyInfo method needs some parameter validation. Also, properties certainly aren’t the only thing we can reflect upon. What about fields, methods and constructors? Here’s a full implementation:

using System;
using System.Linq.Expressions;
using System.Reflection;

public static class StaticReflectorExtensions
{
    public static PropertyInfo PropertyInfo<T, U>(this IStaticReflector<T> obj, Expression<Func<T, U>> selector)
    {
        if (selector == null)
        {
            throw new ArgumentNullException(Strings.Selector);
        }

        PropertyInfo pi = obj.MemberInfo(selector) as PropertyInfo;

        if (pi == null)
        {
            throw new ArgumentException(Strings.InvalidPropertySelector, Strings.Selector);
        }

        return pi;
    }

    public static FieldInfo FieldInfo<T, U>(this IStaticReflector<T> obj, Expression<Func<T, U>> selector)
    {
        if (selector == null)
        {
            throw new ArgumentNullException(Strings.Selector);
        }

        FieldInfo fi = obj.MemberInfo(selector) as FieldInfo;

        if (fi == null)
        {
            throw new ArgumentException(Strings.InvalidFieldSelector, Strings.Selector);
        }

        return fi;
    }

    public static MemberInfo MemberInfo<T, U>(this IStaticReflector<T> obj, Expression<Func<T, U>> selector)
    {
        if (selector == null)
        {
            throw new ArgumentNullException(Strings.Selector);
        }

        var body = selector.Body as MemberExpression;

        if (body == null)
        {
            throw new ArgumentException(Strings.InvalidMemberSelector, Strings.Selector);
        }

        if (body.Expression.NodeType != ExpressionType.Parameter)
        {
            throw new ArgumentException(Strings.InvalidMemberSelector, Strings.Selector);
        }

        return body.Member;
    }

    public static MethodInfo MethodInfo<T, U>(this IStaticReflector<T> obj, Expression<Func<T, U>> selector)
    {
        if (selector == null)
        {
            throw new ArgumentNullException(Strings.Selector);
        }

        var body = selector.Body as MethodCallExpression;

        if (body == null)
        {
            throw new ArgumentException(Strings.InvalidMethodSelector, Strings.Selector);
        }

        // instance methods must be called on the parameter
        if (body.Object != null && body.Object.NodeType != ExpressionType.Parameter)
        {
            throw new ArgumentException(Strings.InvalidMethodSelector, Strings.Selector);
        }

        // static methods must be defined in the type of the parameter or a base type
        if (body.Object == null && !body.Method.DeclaringType.IsAssignableFrom(typeof(T)))
        {
            throw new ArgumentException(Strings.InvalidMethodSelector, Strings.Selector);
        }

        return body.Method;
    }

    public static MethodInfo MethodInfo<T>(this IStaticReflector<T> obj, Expression<Action<T>> selector)
    {
        if (selector == null)
        {
            throw new ArgumentNullException(Strings.Selector);
        }

        var body = selector.Body as MethodCallExpression;

        if (body == null)
        {
            throw new ArgumentException(Strings.InvalidMethodSelector, Strings.Selector);
        }

        // instance methods must be called on the parameter
        if (body.Object != null && body.Object.NodeType != ExpressionType.Parameter)
        {
            throw new ArgumentException(Strings.InvalidMethodSelector, Strings.Selector);
        }

        // static methods must be defined in the type of the parameter or a base type
        if (body.Object == null && !body.Method.DeclaringType.IsAssignableFrom(typeof(T)))
        {
            throw new ArgumentException(Strings.InvalidMethodSelector, Strings.Selector);
        }

        return body.Method;
    }

    public static ConstructorInfo ConstructorInfo<T>(this IStaticReflector<T> obj, Expression<Func<T>> selector)
    {
        if (selector == null)
        {
            throw new ArgumentNullException(Strings.Selector);
        }

        var body = selector.Body as NewExpression;

        if (body == null)
        {
            throw new ArgumentException(Strings.InvalidConstructorSelector, Strings.Selector);
        }

        return body.Constructor;
    }

    private static class Strings
    {
        internal const string InvalidFieldSelector = "Invalid field selector";
        internal const string InvalidPropertySelector = "Invalid property selector";
        internal const string InvalidMemberSelector = "Invalid member selector";
        internal const string InvalidMethodSelector = "Invalid method selector";
        internal const string InvalidConstructorSelector = "Invalid constructor selector";
        internal const string Selector = "selector";
    }
}


Next time, we’ll talk about the disadvantages of this approach, and we’ll look at an alternative.


Comments (71) -

February 23. 2010 01:14 AM

commercial coffee grinder

I admire the valuable information you offer in your articles. I will bookmark your blog and have my children check up here often. I am quite sure they will learn lots of new stuff here than anybody else!

commercial coffee grinder

February 23. 2010 01:51 AM

no loss robot

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.

no loss robot

February 23. 2010 11:17 PM

make money online

I admire what you have done here. I like the part where you say you are doing this to give back but I would assume by all the comments that this is working for you as well.

make money online

February 24. 2010 03:14 AM

eCover Action Graphics

I have recently started using the blogengine.net and I having some problems here? in your blog you stated that we need to enable write permissions on the App_Data folder...unfortunately I don't understand how to enable it.

eCover Action Graphics

February 25. 2010 08:49 PM

shop a lu

Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!

shop a lu

February 25. 2010 10:00 PM

electronic cigarette

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

electronic cigarette

February 26. 2010 02:11 AM

Wealthy Affiliate Scam

I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

Wealthy Affiliate Scam

February 28. 2010 01:24 AM

raw food diet recipes

Hi webmaster, commenters and everybody else !!! The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!b Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do!

raw food diet recipes

February 28. 2010 02:42 AM

Revitol

I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

Revitol

February 28. 2010 03:02 AM

Indonesia Java International Destination

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.

Indonesia Java International Destination

March 1. 2010 01:37 PM

RoweHester

Every one acknowledges that modern life seems to be not very cheap, but people require cash for different stuff and not every person gets big sums cash. So to receive fast <a href="lowest-rate-loans.com/.../personal-loans">personal loans</a> and just financial loan should be a correct solution.

RoweHester

March 2. 2010 12:42 AM

Linkbuilding Tool

Valuable information and excellent design you got here! I would like to thank you for sharing your thoughts and time into the stuff you post!! Thumbs up

Linkbuilding Tool

March 2. 2010 01:09 AM

LARP Weapons

How-do-you-do, just needed you to know I have added your site to my Google bookmarks because of your extraordinary blog layout. But seriously, I think your site has one of the freshest theme I've came across. It really helps make reading your blog a lot easier.

LARP Weapons

March 2. 2010 11:39 PM

how to win back ex

Hey - nice blog, just looking around some blogs, seems a pretty nice platform you are using. I'm currently using Wordpress for a few of my sites but looking to change one of them over to a platform similar to yours as a trial run. Anything in particular you would recommend about it?

how to win back ex

March 2. 2010 11:47 PM

car title loan flagstaff

Do you accept guest posts? I would love to write couple articles here.
I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

car title loan flagstaff

March 3. 2010 12:50 AM

Maplewood NJ Plumbing

I admire the valuable information you offer in your articles. I will bookmark your blog and have my children check up here often. I am quite sure they will learn lots of new stuff here than anybody else!

Maplewood NJ Plumbing

March 3. 2010 09:38 PM

roulette strategie

Well, this is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a marvellous job!

roulette strategie

March 3. 2010 10:47 PM

How To Lose Weight Fast

Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post.

How To Lose Weight Fast

March 3. 2010 11:15 PM

Mountainside NJ HVAC

The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!

Mountainside NJ HVAC

March 5. 2010 06:32 AM

boards

Couldn?t be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks for sharing!

boards

March 5. 2010 12:30 PM

boards

Great post! I am just starting out in community management/marketing media and trying to learn how to do it well - resources like this article are incredibly helpful. As our company is based in the US, it?s all a bit new to us. The example above is something that I worry about as well, how to show your own genuine enthusiasm and share the fact that your product is useful in that case.

boards

March 5. 2010 04:00 PM

diet pill reviews

Very valuable and useful post.this is about "Static Reflection” seem to be the latest type.Reflection is used to obtain information about the code you are executing, and to use that information to interact with the code dynamically. Nice information.
Thanks for sharing.

diet pill reviews

March 5. 2010 11:48 PM

boards

I have recently started using the blogengine.net and I having some problems here? in your blog you stated that we need to enable write permissions on the App_Data folder...unfortunately I don't understand how to enable it.

boards

March 6. 2010 05:34 AM

forum

I have recently started using the blogengine.net and I having some problems here? in your blog you stated that we need to enable write permissions on the App_Data folder...unfortunately I don't understand how to enable it.

forum

March 6. 2010 10:48 AM

boards

There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game.

boards

March 7. 2010 12:37 AM

sauna

Excellent read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that: Thanks for lunch!

sauna

March 7. 2010 12:52 AM

peg perego aria stroller review

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

peg perego aria stroller review

March 8. 2010 09:51 AM

Umbrella Companies

There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game.

Umbrella Companies

March 8. 2010 09:51 AM

Umbrella Companies

There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game.

Umbrella Companies

March 9. 2010 05:02 AM

Webthesurfi Rugs Webdesign

blog hopping...nice blog

Webthesurfi Rugs Webdesign

March 9. 2010 05:03 AM

Watch Pacquiao Vs Clottey Live online

nice blog i learn a lot from it.
Thanks for sharing.

regards,

rosela

Watch Pacquiao Vs Clottey Live online

March 9. 2010 05:18 AM

Emilie Dearth

This is a superb post, but I was wondering how do I suscribe to the RSS feed?

Emilie Dearth

March 9. 2010 05:18 AM

Billie Ganer

I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites blog list and will be checking back soon. Please check out my site as well and let me know what you think.

Billie Ganer

March 9. 2010 05:37 AM

cinsellik

I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post. Big thanks for the useful info ..

cinsellik

March 10. 2010 12:37 AM

wholesale distributors

I was looking for crucial information on this subject. The information was important as I am about to launch my own portal. Thanks for providing a missing link in my business.

wholesale distributors

March 10. 2010 01:43 AM

Communication Skills

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

Communication Skills

March 10. 2010 06:05 AM

arac sorgulama

Interesting post and I really like your take on the issue. I now have a clear idea on what this matter is all about. Thank you so much.

arac sorgulama

March 10. 2010 06:05 AM

arac sorgulama

Interesting post and I really like your take on the issue. I now have a clear idea on what this matter is all about. Thank you so much.

arac sorgulama

March 10. 2010 06:05 AM

arac sorgulama

Interesting post and I really like your take on the issue. I now have a clear idea on what this matter is all about. Thank you so much.

arac sorgulama

March 10. 2010 06:27 AM

portland bankruptcy attorney

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

portland bankruptcy attorney

March 10. 2010 07:26 AM

portland dui attorneys

Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!

portland dui attorneys

March 10. 2010 08:13 AM

adwords consultants

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

adwords consultants

March 10. 2010 11:13 AM

portland divorce lawyer

The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!

portland divorce lawyer

March 11. 2010 11:50 AM

adwords consulting

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

adwords consulting

March 12. 2010 12:53 AM

T1 Internet

Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

T1 Internet

March 12. 2010 01:44 AM

earning money online

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

earning money online

March 12. 2010 02:59 AM

nanny

Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post.

nanny

March 12. 2010 04:06 AM

WorldWide Brands

Do you accept guest posts? I would love to write couple articles here.
I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

WorldWide Brands

March 12. 2010 11:48 AM

Selling Gold

I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.

Selling Gold

March 13. 2010 12:06 AM

hospedagem de sites

really quality post. In theory I'd like to write like this too.

hospedagem de sites

March 13. 2010 11:31 PM

traffic ultimatum bonus

Aw, this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate alot and never seem to get something done.

traffic ultimatum bonus

March 13. 2010 11:53 PM

acne rosacea

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

acne rosacea

March 15. 2010 02:25 AM

New Jersey Car Insurance

Thanks for this -- very useful information!

New Jersey Car Insurance

March 15. 2010 03:27 AM

Indonesia Java International Destination

you put the all great things which makes all people getting interested. but yes thats right, i agree. all you mention is make a sense

Indonesia Java International Destination

March 15. 2010 03:29 AM

webthesurfi rugs webdesign

This so good stuff keep up the good work

webthesurfi rugs webdesign

March 15. 2010 04:07 PM

press release distribution

Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post.

press release distribution

March 15. 2010 09:45 PM

Billye Hele

I don't agree with everything in this article, but you do make some very good points. Im very interested in this subject matter and I myself do alot of research as well. Either way it was a well thoughtout and nice read so I figured I would leave you a comment. Feel free to check out my website sometime and let me know what you think.

Billye Hele

March 15. 2010 09:45 PM

Veronique Dellajacono

This is a very important post, I was looking for this information. Just so you know I discovered your blog when I was looking around for blogs like mine, so please check out my site sometime and leave me a comment to let me know what you think.

Veronique Dellajacono

March 16. 2010 09:54 AM

emekli sandıgı

This is a really good read for me, Must admit that you are one of the best bloggers I ever saw.Thanks for posting this informative article.

emekli sandıgı

March 16. 2010 04:20 PM

acupressure points

Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

acupressure points

March 16. 2010 04:23 PM

beachbody

Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

beachbody

March 16. 2010 04:23 PM

ride on toys

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

ride on toys

March 16. 2010 04:37 PM

train your dog

Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information.

train your dog

March 16. 2010 04:47 PM

best ergonomic chair

There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game.

best ergonomic chair

March 16. 2010 06:42 PM

maytag refrigerator water filter

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon.

maytag refrigerator water filter

March 16. 2010 06:47 PM

best ergonomic chair

There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game.

best ergonomic chair

March 16. 2010 07:20 PM

homeschool program

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

homeschool program

March 16. 2010 07:33 PM

home air conditioning

Hi webmaster, commenters and everybody else !!! The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!b Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do!

home air conditioning

March 16. 2010 08:46 PM

traffic ultimatum review

Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.

traffic ultimatum review

March 17. 2010 01:03 AM

anti aging products

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.

anti aging products

March 17. 2010 01:07 AM

western mediterranean cruises

I thought it was going to be some boring old post, but it really compensated for my time. I will post a link to this page on my blog. I am sure my visitors will find that very useful.

western mediterranean cruises

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Download the U2U brochure

Download Brochure

Receive the U2U Newsletter. Submit your email address:
 
 


 


Search

rss  RSS

Recent posts

None

Archive

Blogroll