Thursday, 3 February 2011

Csharp: Using predicates as arguments.

Question:
How to pass predicates as arguments to my methods?
I want to use predicates as test methods and pass them to a general test.


Answer:
Use the dotNet Predicate<T> Type.
This is a delegate of the form: bool someMethod(T t);

Here is an example

static void Main(string[] args)
{
    Program p = new Program();

    Predicate<string> vow = new Predicate<string>(s => p.HasVowels(s));
    p.TestUsingPredicate(vow);
    Console.WriteLine();

    Predicate<string> upper = new Predicate<string>(s => p.HasUppercaseLetters(s));
    p.TestUsingPredicate(upper);

    Console.ReadLine();

}

void TestUsingPredicate(Predicate<string> yourStringTest)
{
    string[] parts = new string[4] { "baal", "Saul", "cyly", "Brünhym" };
    IEnumerable<string> selection = parts.Where<string>(s => yourStringTest(s));

    selection.ToList<string>().ForEach(s => Console.WriteLine(s));
}

bool HasVowels(string s)
{
    Regex reg = new Regex("a|e|i|o|u");
    return reg.IsMatch(s);
}

bool HasUppercaseLetters(string s)
{
    return s.Any<char>(c => c.ToString() == c.ToString().ToUpper());
}


The result here is:

{"baal", "Saul", "cyly", "Brünhym"}

HasVowels returns:
baal
Saul

HasUppercaseLetters returns :
Saul
Brünhym

No comments: