Kinetic Code Camp - Bring your skills, or lack thereof.. :dumpster_fire:

Just want to add a bit to the delegates, as I’ve played with them a LOT.

If you need to loop through a List<T> (or other types) and perform an Action on each, there’s a shorter syntax you can use. Example:

var NumberList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var EvenNumsOnly = new List<int>();

Action<int> AddEvenNums = i => 
{
    if ( i % 2 == 0 )
    {
        EvenNumsOnly.Add( i );
    }
};

NumberList.ForEach( AddEvenNums );

Another fun thing if you have a simple Func<T> or Action<T>, you can keep them in-line. From the example above, my delegate could be:

Action<int> AddEvenNums = i => if ( i % 2 == 0 ) EvenNumsOnly.Add(i);

or for a Func<T>:

// These two delegates do the same thing:

Func<string,string> ValidateString1 = input =>
{
    if ( string.IsNullOrEmpty(input) )
    {
        return "Invalid Input";
    }
    
    return "Input is Valid";
};

Func<string,string> ValidateString2 = input => string.IsNullOrEmpty(input)? "Invalid Input": "Input is Valid";
1 Like