Use a delegate to call object methods : delegate « delegate « C# / CSharp Tutorial






using System;

public delegate string DelegateDescription();

public class Person
{
  private string name;
  private int age;

  public Person(string name, int age)
  {
    this.name = name;
    this.age = age;
  }

  public string NameAndAge()
  {
    return(name + " is " + age + " years old");
  }

}

public class Employee
{
  private string name;
  private int number;
  public Employee(string name, int number)
  {
    this.name = name;
    this.number = number;
  }

  public string MakeAndNumber()
  {
    return(name + " is " + number + " mph");
  }
}

class MainClass
{
  public static void Main()
  {
    Person myPerson = new Person("Price", 32);
    DelegateDescription myDelegateDescription = new DelegateDescription(myPerson.NameAndAge);

    string personDescription = myDelegateDescription();
    Console.WriteLine("personDescription = " + personDescription);

    Employee myEmployee = new Employee("M", 140);

    myDelegateDescription = new DelegateDescription(myEmployee.MakeAndNumber);

    string d = myDelegateDescription();
    Console.WriteLine(d);
  }
}
personDescription = Price is 32 years old
M is 140 mph








9.1.delegate
9.1.1.Define a delegate with no return value and no parameters
9.1.2.Add both static and non-static function to a delegate
9.1.3.Delegate with reference paramemters
9.1.4.Delegate with return values
9.1.5.Use a delegate to call object methods
9.1.6.delegate is a function pointer
9.1.7.A simple delegate example.
9.1.8.Construct a delegate using method group conversion
9.1.9.Delegates can refer to instance methods
9.1.10.Delegates to Instance Members
9.1.11.uses the invocation list to calculate a factorial
9.1.12.named-delegate invocation
9.1.13.Use delegate to reference two static functions
9.1.14.Declare a delegate and assigns a reference to either the WriteLine method or the ShowWindowsMessage method to its delegate instance.