0

How can I supply a func to a method, so I could write something like:

MethodTest(a => a.IsAltTagAvailable);

Where the signature of this method takes a func which returns an object (say HtmlImage) when the condition is met (basically just a predicate).

Edit: I need to pass the type I will be working on as T (Parameter). I forgot to do this, how clumsy!

Thanks

Chris Farmer
  • 24,974
  • 34
  • 121
  • 164

4 Answers4

3

A predicate tends to return bool, not an object. What are you going to return when the condition isn't met? Given your example, you don't really mean the function returns an object - you mean it takes an object and returns a bool.

Note that if you're going to have a parameter in the lambda expression, you'll need to use a delegate which takes parameters too.

We really need more information before giving a definitive answer, but you might want something like:

void MethodTest(Func<HtmlImage, bool> predicate)

or

void MethodTest(Predicate<HtmlImage> predicate)

(Personally I like the descriptive nature of using a named delegate, but others prefer to use Func/Action for almost everything.)

That's assuming that the type of input is fixed. If not, you might want to make it a generic method:

void MethodTest<T>(Predicate<T> predicate)
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1
void MethodTest(Func<HtmlImage> func) {

}
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
  • @Stefan: based on my understanding of the question he wanted to "Where the signature of this method takes a func which returns an object" which is contradictory to the Lambda he wrote inside his code. – Yuriy Faktorovich Oct 20 '09 at 14:13
1
public void MethodTest(Func<HtmlImage> delegate)
{
 //do what you want
}

OR:

public delegate HtmlImageTagHandler(HtmlImage image);


public HtmlImage MethodTest(HtmlImageTagHandler handler, HtmlImage image)
{
  return handler(image) == true ? image : null;
}

use:

MethodTest(a => a.IsAltTagAvailable, a);
CSharpAtl
  • 7,374
  • 8
  • 39
  • 53
1
void MethodTest(Func<HtmlImage, object> func) 
{

}

HtmlImage is the argument of the function (x), object the return value, you could take the concrete type if you want to specify it.

void MethodTest(Func<HtmlImage, bool> func) 

Which is a predicate:

void MethodTest(Predicate<HtmlImage> func) 

To make it fully generic, replace HtmlImage with a generic argument:

void MethodTest<T>(Predicate<T> func) 
Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193