Arnis Lapsa
Arnis Lapsa

Reputation: 47597

Retrieving static field in generic method by lambda expression

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);

Upvotes: 0

Views: 1327

Answers (2)

Arnis Lapsa
Arnis Lapsa

Reputation: 47597

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500805

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...

Upvotes: 2

Related Questions