private string MyMethod(int testParameter, Func<MyObject, string> selector)
{
return selector(_myObject);
}
When using Func
delegates, the last parameter is the return type and the first N-1 are the argument types. In this case, there is a single MyObject
argument to selector
and it returns a string
.
You can invoke it like:
string name = _myClassInstance.MyMethod(1, x => x.Name);
string result = _myClassInstance.MyMethod(1, x => x.Code);
Since the return type of MyMethod
matches the return type of your selector
delegate, you could make it generic:
private T MyMethod<T>(int testParameter, Func<MyObject, T> selector)
{
MyObject obj = //
return selector(obj);
}
I don’t know VB.Net but it looks like it would be:
Public Function MyMethod(testParameter as Integer, selector as Func(Of MyObject, String))
Return selector(_myObject)
End Function
and the generic version would be:
Public Function MyMethod(Of T)(testParameter as Integer, selector Func(Of MyObject, T))
Return selector(_myObject)
End Function