Lecture – Using Delegates in C Sharp

Using Delegates in C#

Prerequisites

Knowledge of C#

Summary

Students typically struggle with the concepts of delegates in C#, this video demonstrates how delegates are used to allow methods to be passed to methods (or used in expressions)

Video 

Reference Materials

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Delegate_Examples

{

    class Program

    {

        static void Main(string[] args)

        {

            List<SampleObject> list = new List<SampleObject>();

 

            list.Add(new SampleObject("Name 1", false));

            list.Add(new SampleObject("Name 2", true));

 

            Console.Write(list.First<SampleObject>().Name);

            Console.ReadLine();

 

            Console.Write(list.First(delegate (SampleObject so) { return so.nameIsValid() == false; }).Name);

            Console.ReadLine();

 

            Console.Write(list.First<SampleObject>(so => so.nameIsValid() == false).Name);

            Console.ReadLine();

        }

    }

 

    class SampleObject

    {

        public SampleObject(String name)

        {

            Name = name;

        }

 

        public SampleObject(String name, Boolean valid)

        {

            Name = name;

            Valid = valid;

        }

 

 

        public string Name { get; set; }

        public bool Valid { get; set; }

 

        public bool nameIsValid()

        {

            // Some logic will be here

            return Valid;

        }

    }

}

Next: 
Menu Case Study Part 4 – Generating a Javascript call from a Razor Object

Additional Information

COP 4834 Lectures Page