user94893
user94893

Reputation:

How to capture static or non static property by using lambda expression?

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,

Upvotes: 4

Views: 1420

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500815

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

Upvotes: 6

Related Questions