tags:

views:

87

answers:

1

There are a lot of benefits for using lambda expression to capture property or method of some class like the following code.

void CaptureProperty<T, TProperty> (Func<T, TProperty> exp)
{
   // some logic to keep exp variable
}

// So you can use below code to call above method.
CaptureProperty<string, int>(x => x.Length);

However, the above code does not support static property. So, how to create method that support both static property and non-static property?

Thanks,

+6  A: 

Well, you can capture a static property that way:

CaptureProperty<string, Encoding>(x => Encoding.UTF8);

You then need to provide a "dummy" value at execution time though...

An alternative would be to provide another overload with only a single type argument:

void CaptureProperty<T>(Func<T> func)
{
    // Whatever
}

Use is like this:

CaptureProperty<Encoding>(() => Encoding.UTF8);

Is that what you're after?

If you wanted to unify the two internally, you could have a "dummy" private nested type within the same type as CaptureProperty and implement the static version like this:

void CaptureProperty<T>(Func<T> func)
{
    CaptureProperty<DummyType, T>(x => func());
}

Then you could detect that the "source" type is DummyType when you need to call the function later. This may or may not be a useful idea depending on what else you're doing :)

Jon Skeet
Great! Empty parameter expression.
Soul_Master
I just want to convert captured property to something like "{className}.{propertyName}" for sending to JavaScript.
Soul_Master
@Soul_Master: In that case you want `Expression<Func<T>>` rather than `Func<T>`.
Jon Skeet