Question about sum over a dynamic list C#

Viewed 228

Consider a dynamic list

List<dynamic> payments = new List<dynamic>();

Add 2 itens to it

payments.Add(new { value = Convert.ToDecimal("10,35") });
payments.Add(new { value = Convert.ToDecimal("10,35") });

Then sum

var k = payments.Sum(x => (decimal)x.value);
var j = payments.Sum(x => x.value);
var l = payments.Sum(x => Convert.ToDecimal(x.value));

The first one works. Second and third don't. Both throw a "Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?)" My question is... why ? I wanted to understand a bit better the details regarding the differences between the 3 sum examples and why the first one works while the others don't.

Shorter version of the sample still fails:

 (new List<dynamic>(){1m}).Sum(x=>x)

RuntimeBinderException: Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?)

And if you look at generated IL you'll see references to System.Func<System.Object,System.Int32>..ctor (which somewhat makes sense as complier need to pick a type for Func...)

TL;DR: why C# compiler picks Int32 version of Sum (likely at compile time) for dynamics.

0 Answers
Related