mburke05 mburke05 - 1 year ago 150
C# Question

IEnumerable / Enumerable with Double/Int; Beginner

I'm new to C# coming from python, and am unclear on exactly how the

object behaves, even after having read the MSDN documentation.

For instance, the
requires an int, but the following code works fine:

IEnumerable<double> squares = Enumerable.Range(1, 100).Select(x => Math.Pow(x, 2));


IEnumerable<double> square_ = Enumerable.Range(1, 100);

Throw's the compilation error that you cannot implicitly convert type 'System.Collections.Generic.IEnumerable int' to 'System.Collections.Generic.IEnumerable double'

I'm not really sure if this is just a fundamental misunderstanding of how Enumerable works, how objects work in C#, or something else entirely, and would greatly appreciate help and some guidance on where to read for a novice to get a better idea.

Thanks very much in advance.

Answer Source

Because Math.Pow returns a double, so the .Select(x => Math.Pow(x, 2)); returns a IEnumerable<double>, so exactly the type you declared.

The Enumerable.Range returns a IEnumerable<int> that isn't compatible with a IEnumerable<double>.

Clearly you could:

IEnumerable<double> squares = Enumerable.Range(1, 100).Select(x => (double)x);

This would cast the single elements of the Enumerable.Range to double, by using a lambda function int -> double (that from an int x returns a double)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download