Search code examples
c#visual-studio-2008xna

Declare, Instantiate, and Use a Delegate in C# XNA


I am trying to do as the title suggests, however I am getting confused.

I get the idea of how the delegate is supposed to work, but Visual Studio is telling me i'm wrong. Microsoft documentation that says how to do this contains a convoluted example that uses a bookstore program that contains templates and a bunch of logic code that makes it hard to follow.

How do you do this? Thanks.


Solution

  • I assume, in your example, that you want the SetGameAreaWithCallback method to actually call the changeGameArea method on an instance of Game1.

    To do this you need to create your delegate instance so that it refers to that method:

    // game1 is the instance of the Game1 class that you want to call
    // Instantiate the handler
    SetGameAreaDelegate handler = new SetGameAreaDelegate(game1.changeGameArea);
    

    If you're using C#2 or above then the syntax is even simpler:

    // game1 is the instance of the Game1 class that you want to call
    // Instantiate the handler
    SetGameAreaDelegate handler = game1.changeGameArea;