Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "correct" way to initialize a C# delegate?

C# delegates have always been difficult for me to grasp and so I was very happy to stumble across logicchild's article on The Code Project web site titled "C# Delegates: Step by Step". He has a very succinct way of explaining C# delegates and I can recommend it to you. However, in trying out the examples, I see that are two ways to initialize a delegate, mainly:

    //create a new instance of the delegate class
    CalculationHandler sumHandler1 = new CalculationHandler(math.Sum);
    //invoke the delegate
    int result = sumHandler1(8, 9);
    Console.WriteLine("Result 1 is: " + result);

and

    CalculationHandler sumHandler2 = math.Sum;
    //invoke the delegate
    int result = sumHandler2(8, 9);
    Console.WriteLine("Result 2 is: " + result);

where the math class is defined as

public class math
{
    public int Sum(int x, int y)
    {
        return x + y;
    }
}

So which is the "correct" way and why?

like image 793
VinceJS Avatar asked Sep 20 '10 11:09

VinceJS


People also ask

How do you initialize in C?

Different ways of initializing a variable in Cint a, b; a = b = 10; int a, b = 10, c = 20; Method 5 (Dynamic Initialization : Value is being assigned to variable at run time.)

What is the correct way of initializing an array in C?

Array Initialization Using a Loop An array can also be initialized using a loop. The loop iterates from 0 to (size - 1) for accessing all indices of the array starting from 0. The following syntax uses a “for loop” to initialize the array elements. This is the most common way to initialize an array in C.

What is the correct way to initialize array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

Why do we initialize with 0 in C?

In C programming language, the variables should be declared before a value is assigned to it. In an array, if fewer elements are used than the specified size of the array, then the remaining elements will be set by default to 0.


1 Answers

They are both correct, but method group conversion, which is the second option was added in 2.0 (IIRC). I.e. if you're using an old version of the compiler you need to use the first option. Otherwise the extra typing is really redundant.

like image 181
Brian Rasmussen Avatar answered Oct 26 '22 01:10

Brian Rasmussen