Things in C# you might have missed
fekberg.com
fekberg.com
But beware with yield-return, you have to be very conscious of the execution model of LINQ. Take for example this piece of code:
IEnumerable<string> Readlines(Stream io)
{
while(io.CanRead)
{
io.Read(buffer, 0, bufferLength)
... do things with buffer and get a line...
yield return line;
}
}
IEnumerable<string> ReadFileLines(string filename)
{
IEnumerable<string> lines
using(FileStream file = new FileStream(filename))
{
lines = ReadLines(file);
}
return lines;
}
This would always fail and throw an exception. Why? When you call ReadLines, the actual object that is returned is not the list of strings. ReadLines is not executed until that list is not enumerated. ReadFileLines opens the stream, passes it as an argument and then closes the stream. When you enumerate that list, ReadLines will start and try to access a closed stream, which causes an exception. Read more here: http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-...EDIT: Another problem that you could face with deferred execution is that you could execute a method multiple times without noticing.
var lines = ReadLines(file);
var count = lines.Count();
var text = lines.Aggregate("", (acc, x) => x + acc);
This would read all the lines two times (one for count and another for aggregate), and would probably throw another exception because the EOF had been reached in the first execution. In other situations you could have a ultra-slow function because you're executing a heavy function with yield-return multiple times.This is not a problem of yield-return on itself (as SideburnsOfDoom says, it's as easy as calling ToList()), but should remind you that using yield-return everywhere instead of lists is not a good idea.
lines = ReadLines(file).ToList();
ToList() is the go-to method to force eager evaluation of a lazy enumeration.And as you note, enumerating it twice can mean doing the underlying query twice, with potentially differing results.
using Super.Long.Namespace.Utilities
Can be used as: using Utils = Super.Long.Namespace.Utilities
Using C# since 2.0 and only learned about this a month ago! private static bool GreaterThanOne(int @int)
{
return @int > 1;
}
However, it would seem to me to fall into the "never, ever use this" category.... however the coding guidelines are to use the language keyword (i.e. "string" ) where you can.
http://stackoverflow.com/questions/9033/hidden-features-of-c
The question is closed, but there are plenty of interesting answers.
One caveat: some idioms may seem really smart and/or terse, but others may have trouble understanding such code at at glance.