GurdeepS
GurdeepS

Reputation: 67243

What function will a delegate point two if there is more than one method which meets the delegate criteria?

A delegate is a function pointer. So it points to a function which meets the criteria (parameters and return type).

This begs the question (for me, anyway), what function will the delegate point to if there is more than one method with exactly the same return type and parameter types? Is the function which appears first in the class?

Thanks

Upvotes: 0

Views: 242

Answers (3)

Orion Edwards
Orion Edwards

Reputation: 123662

So it points to a function which meets the criteria (parameters and return type).

Nope.

To add some background to Henk's Answer:
Just like int x is an variable which can contain integers, A delegate is a variable which can contain functions.

It points to whatever function you tell it to point to.
EG:

// declare the type of the function that we want to point to
public delegate void CallbackHandler(string); // 

...

// declare the actual function
public void ActualCallbackFunction(string s){ ... }

...
// create the 'pointer' and assign it
CallbackHandler functionPointer = ActualCallbackFunction;
// the functionPointer variable is now pointing to ActualCallbackFunction

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502716

As Henk says, the method is specified when you create the delegate. Now, it's possible for more than one method to meet the requirements, for two reasons:

  • Delegates are variant, e.g. you can use a method with an Object parameter to create an Action<string>
  • You can overload methods by making them generic, e.g.

    static void Foo() {}
    static void Foo<T>(){}
    static void Foo<T1, T2>(){}
    

The rules get quite complicated, but they're laid down in section 6.6 of the C# 3.0 spec. Note that inheritance makes things tricky too.

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273571

The exact method is specified when you create the Delegate.

public delegate void MyDelegate();

private void Delegate_Handler() { }

void Init() {
  MyDelegate x = new MyDelegate(this.Delegate_Handler);
}

Upvotes: 3

Related Questions