Jogi
Jogi

Reputation: 1

having trouble using delegates in c#

With the use of delegates, I want number 5 from IEnumerable items to print to the screen by using the following code;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using extended;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<int> cities = new[] { 1, 2, 3, 4, 5 };
            IEnumerable<int> query = cities.StartsWith(hello);

            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
        static int hello(int x)
        {
        return x > 4 ? x : 0;
        }
    }
}
namespace extended
{
    public static class A
    {
        public static IEnumerable<T> StartsWith<T>(this IEnumerable<T> input, inputdelegate<T> predicate)
        {
            foreach (var item in input)
            {
                if (item.Equals(predicate))
                {
                    yield return item;
                }
            }
        }
        public delegate int inputdelegate<T>(T input);
    }
}

code compiles without any error but displays no output to the screen. Any idea where I might be going wrong?

Upvotes: 1

Views: 35

Answers (1)

Tyree Jackson
Tyree Jackson

Reputation: 2608

You are not invoking your predicate. Also, inputdelegate should probably have a return type of T. Change your code to this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using extended;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<int> cities = new[] { 1, 2, 3, 4, 5 };
            IEnumerable<int> query = cities.StartsWith(hello);

            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
        static int hello(int x)
        {
        return x > 4 ? x : 0;
        }
    }
}
namespace extended
{
    public static class A
    {
        public static IEnumerable<T> StartsWith<T>(this IEnumerable<T> input, inputdelegate<T> predicate)
        {
            foreach (var item in input)
            {
                if (item.Equals(predicate(item)))
                {
                    yield return item;
                }
            }
        }
        public delegate T inputdelegate<T>(T input);
    }
}

UPDATE: Based on comments from AlexD, you should consider changing your test to:

if (predicate(item))

and updating your delegate to:

public delegate bool inputdelegate<T>(T input);

and updating your Hello function to:

static bool hello(int x)
{
    return x > 4;
}

Upvotes: 1

Related Questions