Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Created August 31, 2015 18:35
Show Gist options
  • Save softwarespot/d4ff6c456dadaeaf3d25 to your computer and use it in GitHub Desktop.
Save softwarespot/d4ff6c456dadaeaf3d25 to your computer and use it in GitHub Desktop.
Example of creating a custom delegate, Func types and lambda expressions
using System;
using System.Collections.Generic;
using System.Linq;
namespace ScratchPad
{
public static class Program
{
// Create a custom delegate
public delegate int MyCustomDelegate(int value);
// An example of an extension method for integer datatypes
public static void Print(this int value)
{
// Print the value to the console e.g. 10.Print() would print "10\n"
Console.WriteLine(value);
}
// An example of an extension method using a predicate (function that returns true or false)
// The first parameter is either a list or array e.g. a type that inherits from IEnumerable
public static bool HasValue<T>(this IEnumerable<T> source, Predicate<T> predicate)
{
foreach (var value in source)
{
if (predicate(value))
{
return true;
}
}
return false;
}
private static void Main()
{
// Print the value
10000000.Print();
// Use the custom delegate to create a predicate function
MyCustomDelegate predicate = i => i * 2;
Console.WriteLine(predicate(100));
string[] array = { "10", "11", "12", "13", "14" };
// Example of the .NET extension method .Any()
var hasValue = array.HasValue(s => s == "10");
Console.WriteLine(hasValue);
// Example of using LINQ
var items = new List<string>
{
"String 1",
"String 2",
"",
"String 3",
null,
"String 4"
};
// Iterate over the the following items that aren't null or empty
foreach (var item in items.Where(item => !String.IsNullOrEmpty(item)))
{
Console.WriteLine(item);
}
// Create a delegate function with 2 integer params and a boolean return
Func<int, int, bool> example = (a, b) => a == b;
Console.WriteLine(example(10, 10));
// Example of using a Lambda expression and predefined method
Func<int, string> someMethod = x => (100 * x).ToString();
Console.WriteLine(someMethod(100));
Console.WriteLine("Enter any key to continue. . .");
Console.ReadKey(true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment