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?
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.)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With