Home > C# and dot NET > Func C#

Func C#

Func adalah delegate yang mempunyai zero, satu atau lebih input parameter dan mengembalikan value/reference. Kita dapat menggunakan Func untuk merepresentasikan method yang dapat di-pass sebagai parameter tanpa mendeklarasikan delegate secara explisit.

Berikut ini syntax Func

delegate TResult Func ();
delegate TResult Func (T arg);
delegate TResult Func (T1 arg1, T2 arg2);
.. and so on, up to T16

Example.

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

namespace AppBasicConsole
{
class Program
{
public static IEnumerable GetNumbers(IEnumerable numbers, Func numberResolver)
{
foreach (int number in numbers)
if (numberResolver(number))
yield return number;
}

static void Main(string[] args)
{

IEnumerable numbers = new[] { 1, 2, 3, 5, 4, 6, 7, 27, 8, 13, 21, 32, 9, 11, 14, 24};

IEnumerable greaterThanSeven = GetNumbers(numbers, x => x > 7);
greaterThanSeven.ToList().ForEach(Console.WriteLine);

Console.WriteLine("--------------");

IEnumerable greaterThanOneAfterDividedByEleven = GetNumbers(numbers, n => (n / 11) > 1);
greaterThanOneAfterDividedByEleven.ToList().ForEach(Console.WriteLine);

}
}
}

Capture screen.

Func Delegate

Func Delegate

Referensi : dari berbagai sumber.

Semoga bermanfaat.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: