Use delegates to choose function at runtime

I am new to C# and still understanding the concept of delegates. What I know of delegates is that delegates define a function signature and functions with the same signature can be added to that delegate.

public class ss
{
    public delegate void sampleDelegate();

    public ss()
    {
        sampleDelegate s1 = new sampleDelegate(sampleMethod);
        s1+= new sampleDelegate(sampleMethod2);
        s1();
    }


    public static void sampleMethod()
    {

    }
    public static void sampleMethod2()
    {

    }
}

In the above code I create a delegate and give it sampleMethod and sampleMethod2. When I call s1() it calls both sampleMethod() and sampleMethod2().

What if I want to only call one of those methods and that decision is to be made at runtime?

I may be missing something very small but delegates are really confusing to understand.

Jon Skeet
people
quotationmark

What if i want to only call one of those methods and that decision is to be made at runtime?

Then you don't combine them together, basically. For example:

// Names changed to be more conventional

SampleDelegate s1 = someCondition
    ? new SampleDelegate(SampleMethod)
    : new SampleDelegate(SampleMethod2);
// This will call either SampleMethod or SampleMethod2, depending on condition
s1(); 

Note that normally I'd use a method group conversion, but you can't use method groups for the second and third operands of the conditional operator. You could use:

SampleDelegate s1;
if (condition) {
    s1 = SampleMethod;
} else {
    s2 = SampleMethod2;
}

... or

SampleDelegate s1 = someCondition
    ? new SampleDelegate(SampleMethod)
    : SampleMethod2;

Neither of these looks particularly nice to me though.

people

See more on this question at Stackoverflow