Demonstrate using a generic delegate. - CSharp Custom Type

CSharp examples for Custom Type:Generics

Description

Demonstrate using a generic delegate.

Demo Code

using System;/*from  w  w w.j av  a  2 s  .  c  o  m*/
class Program
{
   delegate TReturn MyAction<TReturn, UParam>(UParam aParam);
   static void Main(string[] args)
   {
      MyAction<int, string> act = new MyAction<int, string>(Program.AMethod);
      int result = act("antidisestablishmentarianism");
      Console.WriteLine("Length of word is {0}", result);
      MyAction<Student, string> act2 = Program.Method2;
      Student aStudent = act2("Marco");
      Console.WriteLine("Student's name is {0}", aStudent.Name);
      MyAction<int, int> act3 = delegate(int param) { return param; };
      Console.WriteLine("Result is {0}", act3(4));
      string name = GetNumberName(4, (n) => "four" );
      Console.WriteLine("Number name for number 4 = {0}", name);
   }
   static int AMethod(string itsOneParam)
   {
      return itsOneParam.Length;
   }
   static Student Method2(string name)
   {
      Student s = new Student();
      s.Name = name;
      return s;
   }
   static string GetNumberName(int number, MyAction<string, int> act)
   {
      return act(number);
   }
}
public class Student
{
   public string Name { get; set; }
}

Result


Related Tutorials