views:

88

answers:

2

Let's say i got this:

public class Foo{
    public string Bar;
}

Then i want to create a 'static reflection' to retrieve value of Bar like this:

public void Buzz<T>(T instance, Func<T, string> getProperty){
    var property = getProperty(instance);        
}

That should work. But what if Foo looks like this?

public class Foo{
    public static string Bar = "Fizz";
}

Can i retrieve value of Bar without passing instance of Foo?

Usage should look like:

var barValue = Buzz<Foo>(foo=>foo.Bar);
+2  A: 

You'd pass in a lambda which ignored its parameter, and use default(T) for the "instance" to use:

var barValue = Buzz<Foo>(x => Foo.Bar);

I suspect I'm missing your point somewhat though...

Jon Skeet
This is where idea came from - http://www.delphicsage.com/home/blog.aspx/d=131/title=Using_Net_3x_Lambda_Expressions_to_Write_More_Concise_Code
Arnis L.
Sorry for being so vague - problem is that i'm feeling quite uncomfortable at this topic (trying to change that). But you hammered the nail... again...
Arnis L.
A: 
class Program
    {
        static void Main()
        {
            Buzz<Foo>(x => Foo.Bar);
        }

        public static void Buzz<T>(Func<T, string> getPropertyValue)
        {
            var value = getPropertyValue(default(T));
            //value=="fizz" which is what i needed
        }
    }

    public class Foo
    {
        public static string Bar = "fizz";
    }

Thanks Jon.

Arnis L.