Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is short.Parse a property or a method?

Tags:

c#

.net

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?

like image 430
snippetkid Avatar asked Dec 25 '22 10:12

snippetkid


2 Answers

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.

like image 184
Charles Mager Avatar answered Jan 12 '23 01:01

Charles Mager


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.

like image 28
Jonathan Wood Avatar answered Jan 12 '23 00:01

Jonathan Wood