I've used short.Parse(somestring)
in the past. But recently I've seen a confusing usage of short.Parse()
like below:
var shortArray = Array.ConvertAll(stringArr, short.Parse);
So, Array.ConvertAll
expects an array and a converter. Well, fine! But how are we passing the short.Parse
as (or like) a property? I don't find such a property in Int16
struct. So, what is happening here actually?
Array.ConvertAll
takes an instance of a Converter<TIn, TOut>
delegate as its second parameter. The signature of this delegate is substantially the same as short.Parse
- both return a value for a single argument.
The compiler will convert a 'method group' to a compatible delegate. This is known as implicit method group conversion.
For comparison, the explicit creation of the delegate would look like this:
Array.ConvertAll(stringArr, new Converter<string, short>(short.Parse));
So, to answer you question: it's still a method, not a property. What you are doing here is passing the method as a delegate. You are providing ConvertAll
with a function to call: when it converts an element in the source array, it will execute short.Parse(element)
and use the value returned in the new array.
short.Parse
is a method. But it is possible to pass a method as an argument.
Note the difference between calling a method and passing the value returned by that method (short.Parse()
), and passing the method itself (short.Parse
).
Internally, this would be passing the address of the method so that the receiver of that argument can call it.
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