I am new to C# and found a method I can't quite finish making work. The method is supposed to take an array and return it with all integers squared.
What I don't understand is the <long>
return type or why it would be needed and the fact that if an item that is more than int's MaxValue is passed, then the method doesn't change it in any way when it's supposed to return it as 0.
What I want is if an array like new long[] {4294967296, 4295098369, 4611686014132420609}
is passed to it, it would return {0, 0, 0}
using System;
using System.Collections.Generic;
using System.Linq;
namespace EnumerableTask
{
public class EnumerableManipulation
{
public IEnumerable<long> GetSquareSequence(IEnumerable<int> data)
{
/// <summary>Transforms integer sequence to its square sequence
/// <param name="data">Source int sequence.</param>
/// Returns sequence of squared items.
foreach (int item in data)
{
if (item == null)
{
yield return 0;
}
else if (item > int.MaxValue)
{
yield return 0;
}
yield return item * item;
///For some reason just returns an item's value if it's more than int.MaxValue. Why?
}
}
}
}
long
return type is easy to explain:int.MaxValue
squared doesn't fit in anint
, but it does fit in along
. To actually perform the calculation so it yields along
, however, you have to convert the operand first:yield return (long) item * item
. Note that the test fornull
is entirely useless and the compiler should have told you so: anint
is nevernull
. Nor is anint
ever greater thanint.MaxValue
, by definition, so the whole thing can be simplified to just theyield
. - Jeroen MostertIEnumerable<long>
. Otherwise, you will have overflow as now. - kosistInt32
is 46,340. Everything above that will overflow. - Steven