Skip to content

Instantly share code, notes, and snippets.

@AndrewBarfield
Created April 30, 2012 08:09
Show Gist options
  • Save AndrewBarfield/2556440 to your computer and use it in GitHub Desktop.
Save AndrewBarfield/2556440 to your computer and use it in GitHub Desktop.
C#: delegate: Calling static and instance methods with delegates
using System;
namespace DelegateExample {
class Program {
// Declares a delegate for the methods
public delegate String myMethodDelegate();
// Defines an instance and static method
public class myMethodsClass {
public String InstanceMethod() {
return ( "I'm an instance Method!" );
}
public static String StaticMethod() {
return ( "I'm a static Method!" );
}
}
static void Main(string[] args) {
// Creates a methodsClass instance
myMethodsClass methodsClass = new myMethodsClass();
// Creates delegate instances
myMethodDelegate myD1 = new myMethodDelegate( methodsClass.InstanceMethod );
myMethodDelegate myD2 = new myMethodDelegate( myMethodsClass.StaticMethod );
// Invokes the delegates.
Console.WriteLine( "{0}", myD1() );
Console.WriteLine( "{0}", myD2() );
// Allows user to view the results
Console.Read();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment