Directory Freebies VS CheatSheet Forum

RSS

Email

Translate

Home About Archive Privacy Contact Advertise Write for Dev102
Posted by moshe on Jul 28th, 2009 | Filed under .Net, C# | 5 Comments

Last week, I stumbled upon the following piece of code:

 

IList<double> doubles = new List<double> {22.123, 400.12, 100.22};
foreach (int number in doubles)
{
    Console.WriteLine("The Current Number Is : {0}", number);
}

Can you see the bug in that code? We convert all of the doubles in the list to integers, truncating them. I was very surprised that the compiler didn’t warn me about this issue, especially because the compiler would not let me write this code:

 


Continue Reading...
Posted by Amit on Jan 5th, 2009 | Filed under .Net, C# | 10 Comments

Here we are talking about filtering list items again :). I got two comment suggesting the use of yield return.

James Curran said:

Don’t build a new list if you don’t have to.

private static IEnumerable EvenSlicker_FilterPositiveItems(IEnumerable t)

{

foreach(int n in t)

if (n > 0)

yield return n;

}

The advantage is if you try using the method this this:

foreach(int n in FilterPositiveItems(myList) {…}

Your way is O(2N) while mine is O(N)


Continue Reading...
Write Article for Dev102

Write for Dev102!

We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution

Learn More