Site: http://msmvps.com/blogs/jon_skeet/default.aspx Link: http://feeds.feedburner.com/JonSkeetCodingBlog
by skeet via Jon Skeet: Coding Blog on 12/5/2011 7:26:25 PM
(As usual, I will be sending the publisher a copy of this review to give them and the author a chance to reply to it before I publish it to the blog. Other than including their comments and correcting any factual mistakes they may point out, I don't intend to change the review itself.) Resources: Publisher page (includes source code download) Amazon / Barnes and Noble My unofficial errata and notes A more positive series of review blog posts (just for balance) Introductio ...
[ read more ]
by skeet via Jon Skeet: Coding Blog on 11/25/2011 9:46:45 PM
In the last post I showed a method to implement "majority voting" for tasks, allowing a result to become available as soon as possible. At the end, I mentioned that I was reasonably confident that it worked because of the unit tests... but I didn't show the tests themselves. I felt they deserved their own post, as there's a bigger point here: it's possible to unit test async code. At least sometimes. Testing code involving asynchrony is generally a pain. Introducing the ex ...
by skeet via Jon Skeet: Coding Blog on 11/11/2011 10:15:11 PM
Ages ago when I wrote my previous Eduasync post, I said we'd look at a pipeline model of coroutines. I've decided to skip that, as I do want to cover the topic of this post, and I've got some more "normal" async ideas to write about too. If you want to look at the pipeline coroutines code, it's project 20 in the source repository. Have fun, and don't blame me if you get confused reading it - so do I. The code I am going to write about is horrible too. It's almo ...
by skeet via Jon Skeet: Coding Blog on 9/18/2011 7:09:41 AM
EDIT, 17th October 2011: Last week Kobalt closed down... so the choice about whether or not I'd buy from them again is now moot. However, PC Specialist sells a very similar spec, now including the matte screen... As some of you will know, our house was burgled in April, and the thieves took three laptops (and very little else), including my main personal laptop. Obviously I ordered a replacement, partly covered by the insurance from my old laptop. However, I took the opportunity to spoil my ...
by skeet via Jon Skeet: Coding Blog on 8/22/2011 11:06:18 PM
As with almost any performance work, your mileage may vary (in particular the 64-bit JIT may work differently) and you almost certainly shouldn't care. Relatively few people write production code which is worth micro-optimizing. Please don't take this post as an invitation to make code more complicated for the sake of irrelevant and possibly mythical performance changes. It took me a surprisingly long time to find the problem described in the previous blog post, and almost no time at al ...
by skeet via Jon Skeet: Coding Blog on 8/22/2011 9:57:55 PM
As with almost any performance work, your mileage may vary (in particular the 64-bit JIT may work differently) and you almost certainly shouldn't care. Relatively few people write production code which is worth micro-optimizing. Please don't take this post as an invitation to make code more complicated for the sake of irrelevant and possibly mythical performance changes. I've been doing quite a bit of work on Noda Time recently - and have started getting my head round all the work t ...
by skeet via Jon Skeet: Coding Blog on 6/16/2011 6:19:12 PM
This post came out of this Stack Overflow question, which essentially boils down to which is better out of these two options: var oneBigPredicate = collection.Where(x => Condition1(x) && Condition2(x) ...
by skeet via Jon Skeet: Coding Blog on 6/10/2011 9:28:46 PM
(This post covers project 12 in the source code.) Last time, we saw what happens when we have multiple await expressions: we end up with multiple potential states in our state machine. That's all fine, but there's a known bug in the current CTP which affects the code generated when you have multiple awaits in the same statement. (Lucian Wischik calls these "nested awaits" although I personally don't really think of one as being nested inside an another.) This post is most ...
by skeet via Jon Skeet: Coding Blog on 5/30/2011 8:06:10 PM
Last time we looked at a complex async method with nested loops and a single await. This post is the exact opposite - the method is going to look simple, but it will have three await expressions in. If you're glancing down this post and feel put off by the amount of code, don't worry - once you've got the hang of the pattern, it's really pretty simple. Here's the async method we're going to analyze: private static async Task<int> Sum3ValuesAsyncWithAssis ...
by skeet via Jon Skeet: Coding Blog on 5/29/2011 6:30:12 PM
Last time we had a really simple async method, and looked at the generated code. Even that took a little while... but in this post I'll demonstrate some of the intricacies that get involved when the async method is more complex. In particular, this time we have: A parameter to the async method A "using" statement, so we'll need a finally block Two loops The possibility of catching an exception generated from await and retrying I've not made it as complica ...
by skeet via Jon Skeet: Coding Blog on 5/20/2011 6:21:02 PM
In part 6 we tried to come up with a "manual" translation of a very simple async method. This time we'll see what the compiler really generates. As a reminder, here's the async method in question: private static async Task<int> ReturnValueAsyncWithAssistance() { Task<int> task = Task<int>.Factory.StartNew(() => 5); return await task; } Whereas our manual code still ended up ...
by skeet via Jon Skeet: Coding Blog on 5/20/2011 1:36:28 PM
Now that we've got the infrastructure for both returning a task from an async method, and awaiting a Task<T>, we're going to look at what the compiler does for us. I always find that the best way of appreciating a feature like this is to consider what we'd have to do without it. Later on we're going to see what the C# compiler does in terms of decompiling the actual generated code, but first we'll look at what we might do to achieve the same end result, using the same i ...
by skeet via Jon Skeet: Coding Blog on 5/17/2011 7:47:45 PM
In part 3 we looked at what the C# 5 compiler required for you to "await" something. The sample used a class which actually had an instance method called GetAwaiter, but I mentioned that it could also be an extension method. In this post, we'll use that ability to make Task<T> awaitable - at which point we have everything we need to actually see some asynchronous behaviour. Just like the last part, the code here is pretty plain - but by the end of the post we'll have a f ...
by skeet via Jon Skeet: Coding Blog on 5/8/2011 8:05:32 PM
I’ve been waiting to start this blog series for a couple of months. It’s nice to finally get cracking. Hopefully some of you have already read some of my thoughts around C# 5’s async feature, mostly written last year. Since that initial flurry of posts, I’ve been pretty quiet, but I’m still really excited about it. Really, really excited. I’ve given a few talks on it, and I have a few more still to give - and this blog series will partly be complementary to those talks. In particular, there’s a ...
by skeet via Jon Skeet: Coding Blog on 4/5/2011 8:50:47 PM
This post was provoked by a recent Stack Overflow question which asked whether there was an efficient representation of ASCII strings in .NET. In particular, the questioner wanted to story hundreds of thousands - possibly millions - of strings in memory, and knowing (or assuming) that they all consisted of ASCII characters, he wanted to avoid the waste of space that comes from storing each character in a .NET string as a UTF-16 code unit. My answer to the question mostly consisted of saying th ...
by skeet via Jon Skeet: Coding Blog on 2/23/2011 11:20:45 PM
Table of Contents You may consider it a little odd to have a list of posts as the final part in the series, but it makes sense when you consider that visiting the Edulinq tag page shows results in reverse chronological order. At that point, a newcomer will hopefully hit this post first, and then find it easier to navigate to the first post. Anyway... Introduction Where Select Range Empty Repeat Count and LongCount Concat SelectMany Any and All First, ...
by skeet via Jon Skeet: Coding Blog on 2/20/2011 9:18:22 PM
I've been putting off writing about this for a while now, mostly because it's such a huge topic. I'm not going to try to give more than a brief introduction to it here - don't expect to be able to whip up your own LINQ to SQL implementation afterwards - but it's worth at least having an idea of what happens when you use something like LINQ to SQL, NHibernate or the Entity Framework. Just as LINQ to Objects is primarily interested in IEnumerable<T> and the static Enumer ...
by skeet via Jon Skeet: Coding Blog on 1/31/2011 5:55:12 AM
A few parts ago, I jotted down a few thoughts on optimization. Three more topics on that general theme have occurred to me, one of them prompted by the comments. User-directed optimizations I mentioned last time that for micro-optimization purposes, we could derive a tiny benefit if there were operators which allowed us to turn off potential optimizations - effectively declare in the LINQ query that we believed the input sequence would never be an IList<T> or an ICollection<T>, so ...
by skeet via Jon Skeet: Coding Blog on 1/28/2011 6:22:54 AM
Okay, first a quick plug. This won't be in as much detail as chapter 11 of C# in Depth. If you want more, buy a copy. (Until Feb 1st, there's 43% off it if you buy it from Manning with coupon code j2543.) Admittedly that chapter has to also explain all the basic operators rather than just query expression translations, but that's a fair chunk of it. If you're already familiar with query expressions, don't expect to discover anything particularly insightful here. However, you ...
by skeet via Jon Skeet: Coding Blog on 1/26/2011 5:59:40 PM
I'm not an expert in optimization, and most importantly I don't have any real-world benchmarks to support this post, so please take it with a pinch of salt. That said, let's dive into what optimizations are available in LINQ to Objects. What do we mean by optimization? Just as we think of refactoring as changing the internal structure of code without changing its externally visible behaviour, optimization is the art/craft/science/voodoo of changing the performance of code without c ...
by skeet via Jon Skeet: Coding Blog on 1/25/2011 6:50:17 PM
While implementing Edulinq, I only focused on two implementations: .NET 4.0 and Edulinq. However, I was aware that there were other implementations available, notably LinqBridge and the one which comes with Mono. Obviously it's interesting to see how other implementations behave, so I've now made a few changes in order to make the test code run in these different environments. The test environments I'm using Mono 2.8 (I can't remember the minor version number offhand) but I ten ...
by skeet via Jon Skeet: Coding Blog on 1/22/2011 9:25:14 AM
I mentioned before that the Zip operator was only introduced in .NET 4, so clearly there's a little wiggle room for LINQ to Object's query operators to grow in number. This post mentions some of the ones I think are most sorely lack - either because I've wanted them myself, or because I've seen folks on Stack Overflow want them for entirely reasonable use cases. There is an issue with respect to other LINQ providers, of course: as soon as some useful operators are available for ...
by skeet via Jon Skeet: Coding Blog on 1/20/2011 8:09:10 AM
Now that I'm "done" reimplementing LINQ to Objects - in that I've implemented all the methods in System.Linq.Enumerable - I wanted to write a few posts looking at the bigger picture. I'm not 100% sure of what this will consist of yet; I want to avoid this blog series continuing forever. However, I'm confident it will contain (in no particular order): This post: principles governing the behaviour of LINQ to Objects Missing operators: what else I'd have liked ...
by skeet via Jon Skeet: Coding Blog on 1/18/2011 6:49:10 PM
This will be a short interlude from Edulinq, although as it will become obvious, it was in the process of writing the next Edulinq post that I made this discovery. It may be known about elsewhere, but it's the first time I'd come across it - or rather, it's the first time I've considered the impact of the compiler's decisions in this area. Sequences and iterators This post is about details of iterator blocks and memory usage. It's going to be quite important that you ca ...
by skeet via Jon Skeet: Coding Blog on 1/14/2011 10:17:11 PM
Our last operator is the simplest of all. Really, really simple. What is it? AsEnumerable has a single signature: public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerable<TSource> source) I can describe its behaviour pretty easily: it returns source. That's all it does. There's no argument validation, it doesn't create another iterator. It just returns source. You may well be wondering what the point is... and it's all about changing ...
by skeet via Jon Skeet: Coding Blog on 1/14/2011 9:44:38 PM
Zip will be a familiar operator to any readers who use Python. It was introduced in .NET 4 - it's not entirely clear why it wasn't part of the first release of LINQ, to be honest. Perhaps no-one thought of it as a useful operator until it was too late in the release cycle, or perhaps implementing it in the other providers (e.g. LINQ to SQL) took too long. Eric Lippert blogged about it in 2009, and I find it interesting to note that aside from braces, layout and names we've got exactl ...
by skeet via Jon Skeet: Coding Blog on 1/14/2011 7:44:45 PM
Nearly there now... What is it? SequenceEqual has two overloads - the obvious two given that we're dealing with equality: public static bool SequenceEqual<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second) public static bool SequenceEqual<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second, & ...
by skeet via Jon Skeet: Coding Blog on 1/13/2011 7:32:13 PM
More design decisions around optimization today, but possibly less controversial ones... What are they? Cast and OfType are somewhat unusual LINQ operators. They are extension methods, but they work on the non-generic IEnumerable type instead of the generic IEnumerable<T> type: public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source) public static IEnumerable<TResult> OfType<TResult>( ...
by skeet via Jon Skeet: Coding Blog on 1/12/2011 6:53:15 PM
After the dubious optimizations of ElementAt/ElementAtOrDefault yesterday, we meet an operator which is remarkably good at defying optimization. Sort of. Depending on how you feel it should behave. What is it? Contains has two overloads, which only differ by whether or not they take an equality comparer - just like Distinct, Intersect and the like: public static bool Contains<TSource>( this IEnumerable<TSource> source, TSourc ...
by skeet via Jon Skeet: Coding Blog on 1/11/2011 11:59:38 PM
A nice easy pair of operators tonight. I should possibly have covered them at the same time as First/Last/Single and the OrDefault variants, but never mind... What are they? ElementAt and ElementAtOrDefault have a single overload each: public static TSource ElementAt<TSource>( this IEnumerable<TSource> source, int index) public static TSource ElementAtOrDefault<TSource>( this IEnumerable&l ...
by skeet via Jon Skeet: Coding Blog on 1/10/2011 8:59:13 PM
This is the final aggregation operator, after which I suspect we won't need to worry about floating point difficulties any more. Between this and the unexpected behaviour of Comparer<string>.Default, I've covered two of my "big three" pain points. It's hard to see how I could get dates and times into Edulinq naturally; it's even harder to see how time zones could cause problems. I've still got a few operators to go though, so you never know... What is it? Av ...
by skeet via Jon Skeet: Coding Blog on 1/9/2011 10:03:05 PM
The second and third AOOOD operators today... if I'm brave enough to tackle Average tomorrow, I'll have done them all. More surprises here today, this time in terms of documentation... What are they? Min and Max are both extension methods with 22 overloads each. Min looks like this: public static int Min(this IEnumerable<int> source) public static int Min<TSource>( this IEnumerable<TSource> source, ...
by skeet via Jon Skeet: Coding Blog on 1/8/2011 3:15:36 PM
Okay, I've bitten the bullet. The first of the four Aggregation Operators Of Overload Doom (AOOOD) that I've implemented is Sum. It was far from difficult to implement - just tedious. What is it? Sum has 20 overloads - a set of 4 for each of the types that it covers (int, long, float, double, decimal). Here are the overloads for int: public static int Sum(this IEnumerable<int> source) public static int? Sum(this IEnumerable<int?> source) ...
by skeet via Jon Skeet: Coding Blog on 1/8/2011 9:44:50 AM
Time for a change of pace after the deep dive into sorting. Reversing is pretty simple... which is not to say there's nothing to discuss, of course. What is it? Reverse only has a single, simple signature: public static IEnumerable<TSource> Reverse<TSource>( this IEnumerable<TSource> source) The behaviour is pretty simple to describe: source cannot be null; this is validated eagerly. The operator uses deferred execution: until you st ...
by skeet via Jon Skeet: Coding Blog on 1/7/2011 7:15:56 PM
I feel I need a voice over. "Previously, on reimplementing LINQ to Objects..." Well, we'd got as far as a working implementation of OrderedEnumerable which didn't have terrible performance - unless you had an expensive key selector. Oh, and it didn't make use of the fact that we may only want the first few results. Executing key selectors only once Our first problem is to do with the key selectors. For various reasons (mentioned in part 26b) life is better if we execute t ...
by skeet via Jon Skeet: Coding Blog on 1/6/2011 7:04:09 PM
Part 26b left us with a working implementation of the ordering operators, with two caveats: The sort algorithm used was awful We were performing the key selection on every comparison, instead of once to start with Today's post is just going to fix the first bullet - although I'm pretty sure that fixing the second will require changing it again completely. Choosing a sort algorithm There are lots of sort algorithms available. In our case, we need the eventual algorithm to: ...
by skeet via Jon Skeet: Coding Blog on 1/5/2011 7:18:59 PM
Last time we looked at IOrderedEnumerable<TElement> and I gave an implementation we could use in order to implement the public extension methods within LINQ. I'm still going to do that in this post, but it's worth mentioning something else that's coming up in another part (26d) - I'm going to revisit my OrderedEnumerable implementation. There may be trouble ahead... A comment on the previous post mentioned how my comparer executes the keySelector on each element every tim ...
by skeet via Jon Skeet: Coding Blog on 1/4/2011 8:28:42 PM
Implementing OrderBy/OrderByDescending/ThenBy/ThenByDescending isn't too bad, once you understand how the pattern works, but that's a slight conceptual leap. I'll take it one step at a time, first introducing some extra infrastructure (both public and internal), then implementing it simply and slowly, and finally optimizing it somewhat. The sorting features of LINQ As a query language, it's natural that LINQ allows you to sort sequences. Of course, collections have had the abil ...
by skeet via Jon Skeet: Coding Blog on 1/2/2011 9:50:45 PM
This one ended up being genuinely easy to implement, although with lots of tests for different situations. What is it? ToDictionary has four overloads which look remarkably similar to the ones we used for ToLookup: public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) public static Dictionary<TKey, TElement> ToDictionar ...
by skeet via Jon Skeet: Coding Blog on 1/2/2011 8:45:12 PM
This really is a simple one. So simple I might even find the energy to implement ToDictionary as well tonight... we'll see. (EDIT: Oops. It became slightly less simple in the end, as I came up with the third implementation. Oh well.) What is it? ToArray is basically the equivalent of ToList, but producing an array instead of a list. It has a single signature: public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source) Just to recap: It's another e ...
by skeet via Jon Skeet: Coding Blog on 1/2/2011 6:45:27 PM
I genuinely expected these operators to be simple. At the time of this writing, I'm onto my third implementation of SkipWhile, struggling to find code which obviously expresses what's going on. I find it interesting how the simplest sounding operators sometimes end up being trickier to implement than one might think. What are they? Take, TakeWhile, Skip and SkipWhile form a natural group of operators. Together they are known as the partitioning operators. Here are the signatures: publ ...
by skeet via Jon Skeet: Coding Blog on 1/1/2011 8:54:06 PM
Another operator that was decidedly easy to implement - partly as I was able to just adapt everything from Join, including the tests. 15 minutes for tests + implementation... and no doubt considerably long writing it up. What is it? After the complexity of GroupBy, GroupJoin has a refreshingly small list of overloads: public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>( this IEnumerable<TOuter> outer, ...
by skeet via Jon Skeet: Coding Blog on 1/1/2011 6:20:46 PM
Okay, after the brief hiatus earlier, we're ready to group sequences. What is it? GroupBy has eight overloads, using up to four type parameters and up to five normal parameters. Those of a sensitive disposition may wish to turn away now: public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) public static IEnu ...
by skeet via Jon Skeet: Coding Blog on 1/1/2011 1:17:29 PM
This morning I started writing the tests for GroupBy, prior to implementing it. That turned out to be a pain - really I wanted an easy way of getting at each element of the result (i.e. each result group). If only I had the ability to convert an arbitrary sequence into a query... I needed ToList. So, we enter a fairly brief diversion. What is it? ToList has a single, simple overload: public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source) Fairly ...
by skeet via Jon Skeet: Coding Blog on 9/3/2010 7:54:46 PM
Warning: this post is quite long. Although I've chosen a simple operator to implement, we'll encounter a few of the corner cases and principles involved in LINQ along the way. This will also be a somewhat experimental post in terms of format, as I try to work out the best way of presenting the material. We're going to implement the "Where" clause/method/operator. It's reasonably simple to understand in general, but goes into all of the deferred execution and streaming ...
by skeet via Jon Skeet: Coding Blog on 9/3/2010 6:37:06 AM
About a year and a half ago, I gave a talk at a DDD day in Reading, attempting to reimplement as much of LINQ to Objects as possible in an hour. Based on the feedback from the session, I went far too fast... and I was still a long way from finishing. However, I still think it's an interesting exercise, so I thought I'd do it again in a more leisurely way, blogging as I go. Everything will be under the "Reimplementing LINQ to Objects" tag, so that's the best way to get all t ...
by skeet via Jon Skeet: Coding Blog on 9/2/2010 6:55:55 AM
Josh Twist asked me this via Twitter: is it possible to invoke a member before a ctor is finished (eg maybe using threaded IL trickery) or is this forbidden somehow? :D Now I don't know why everyone seems to think I enjoy writing code which could have bizarre effects on either you, the compiler, the resulting execution or your co-workers... but it's an interesting topic to look at, anyway. The perils of partially constructed objects Hopefully it's reasonably obvious why it ...
by skeet via Jon Skeet: Coding Blog on 7/29/2010 8:41:06 PM
I had an interesting day at work today. I thought my code had broken... but it turns out it was just a strange corner case which made it work very slowly. Usually when something interesting happens in my code it's quite hard to blog about it, because of all the confidentiality issues involved. In this case, it's extremely easy to reproduce the oddity in an entirely vanilla manner. All we need is the Java collections API. I have a set - a HashSet, in fact. I want to remove some items fro ...
by skeet via Jon Skeet: Coding Blog on 7/27/2010 6:52:23 PM
Do you know the hardest thing about presenting code with surprising results? It's hard to do so without effectively inviting readers to look for the trick. Not that that's always enough - I failed the last of Neal and Eric's C# puzzlers at NDC, for example. (If you haven't already watched the video, please do so now. It's far more entertaining than this blog post.) Anyway, this one may be obvious to some of you, but there are some interesting aspects even when you've got ...
by skeet via Jon Skeet: Coding Blog on 7/25/2010 8:58:03 PM
Yesterday I tweeted a link to an article about overloading that I'd just finished. In that article, all my examples look a bit like this: using System; class Test { static void Foo(int x, int y = 5) { Console.WriteLine("Foo(int x, int y = 5)"); } static void Foo(double x) { ...
by skeet via Jon Skeet: Coding Blog on 3/25/2010 1:41:32 PM
I've been reviewing chapter 10 of C# in Depth, which is about extension methods. This is where I start introducing some of the methods in System.Linq.Enumerable, such as Where and Reverse. I introduce a few pieces of terminology in callouts - and while I believe I'm using this terminology correctly according to MSDN, I suspect that some of it isn't quite what many developers expect... in particular, what does it mean for something to be "lazy"? Let's start off with a q ...
by skeet via Jon Skeet: Coding Blog on 2/10/2010 9:56:00 PM
(Edited on February 11th, 2010 to take account of a few mistakes and changes in the .NET 4.0 release candidate.) I've just been fiddling with the first appendix of C# in Depth, which covers the standard query operators in LINQ, and describes a few details of the LINQ to Objects implementations. As well as specifying which operators stream and which buffer their results, and immediate vs deferred execution, I've where LINQ optimises for different collection types - or where it doesn' ...
by skeet via Jon Skeet: Coding Blog on 1/26/2010 5:48:00 PM
This morning, while checking out an email I'd received about my brain-teasers page, I discovered an interesting change to the CLR in .NET 4.0. At least, I think it's interesting. It's possible that different builds of the CLR have exhibited different behaviour for a while - I only have 32-bit versions of Windows installed, so that's what I'm looking at for this whole post. (Oh, and all testing was done under .NET 4.0b2 - it could still change before release.) Note: to try any ...
by skeet via Jon Skeet: Coding Blog on 1/16/2010 8:13:42 PM
I've been researching Reactive Extensions for the last few days, with an eye to writing a short section in chapter 12 of the second edition of C# in Depth. (This is the most radically changed chapter from the first edition; it will be covering LINQ to SQL, IQueryable, LINQ to XML, Parallel LINQ, Reactive Extensions, and writing your own LINQ to Objects operators.) I've watched various videos from Channel 9, but today was the first time I actually played with it. I'm half excited, and ...
by skeet via Jon Skeet: Coding Blog on 12/9/2009 6:04:47 PM
Warning: here be dragons. I don't think this is the right way to check for null arguments, but it was an intriguing idea. Today on Stack Overflow, I answered a question about checking null arguments. The questioner was already using an extension similar to my own one in MiscUtil, allowing code like this: public void DoSomething(string name) { name.ThrowIfNull("name"); // Normal code here } That's all very well, ...
by skeet via Jon Skeet: Coding Blog on 11/17/2009 7:31:48 AM
Disclaimer: I don't want this to become a flame war in the comments. I'm coming from a position of ignorance, and well aware of it. While I'd like this post to provoke thought, it's not meant to be provocative in the common use of the term. Chapter 14 of C# in Depth is about dynamic typing in C#. A couple of reviewers have justifiably said that I'm fairly keen on the mantra of "don't use dynamic typing unless you need it" – and that possibly I'm doing dynam ...
by skeet via Jon Skeet: Coding Blog on 11/4/2009 7:40:15 AM
Almost every Stack Overflow question which includes the words "random" and "repeated" has the same basic answer. It's one of the most common "gotchas" in .NET, Java, and no doubt other platforms: creating a new random number generator without specifying a seed will depend on the current instant of time. The current time as measured by the computer doesn't change very often compared with how often you can create and use a random number generator – so code whi ...
by skeet via Jon Skeet: Coding Blog on 11/2/2009 10:20:10 PM
(Meta note: I tried to fix the layout for this, I really did. But my CSS skills are even worse than Tony's. If anyone wants to send me a complete sample of how I should have laid this out, I'll fix it up. Otherwise, this is as good as you're going to get :) Last week at Stack Overflow DevDays, London I presented a talk on how humanity had made life difficult for software developers. There's now a video of it on Vimeo - the audio is fairly poor at the very start, but it improves ...
by skeet via Jon Skeet: Coding Blog on 10/31/2009 10:04:54 PM
I've just been going through some feedback for the draft copy of the second edition of C# in Depth. In the contracts section, I have an example like this: [ContractClass(typeof(ICaseConverterContracts))] public interface ICaseConverter { string Convert(string text); } [ContractClassFor(typeof(ICaseConverter))] internal class ICaseConverterContracts : ICaseConverter { string ICaseConverter.Convert(string text ...
by skeet via Jon Skeet: Coding Blog on 10/23/2009 9:20:00 PM
The IEnumerable<T> and IEnumerator<T> interfaces in .NET are interesting. They crop up an awful lot, but hardly anyone ever calls them directly - you almost always use a foreach loop to iterate over the collection. That hides all the calls to GetEnumerator(), MoveNext() and Current. Likewise iterator blocks hide the details when you want to implement the interfaces. However, sometimes details matter - such as for this recent Stack Overflow question. The question asks how to create a ...
by skeet via Jon Skeet: Coding Blog on 9/20/2009 8:48:00 PM
EDIT: Please ignore this post for the moment. It's wrong. I'll leave up the incorrect version for the moment so you can see what it will be about, but it doesn't quite work. The size of Empty ends up being 1, annoyingly enough. I'll edit this post properly when I get the chance. A long time ago, I'm pretty sure I started writing Push LINQ in response to a request to effectively count votes. To recap the example in the linked blog post, I wanted to work out the most popular co ...
Well, this is embarrassing. Yesterday evening, I excitedly wrote a blog post about an interesting little idea for making a particular type of LINQ query (basically vote counting) efficient. It was an idea that had occurred to me a few months back, but I hadn't got round to blogging about it. The basic idea was to take a completely empty struct, and use that as the element type in the results of a grouping query - as the struct was empty, it would take no space, therefore "huge" a ...
by skeet via Jon Skeet: Coding Blog on 9/14/2009 4:38:05 PM
So, UnconstrainedMelody is coming on quite nicely. It now has quite a few useful options for flags enums, "normal enums" and delegates. However, there are two conflicting limitations which leave a couple of options. (Other related answers on Stack Overflow have suggested alternative approaches, basically.) Currently, most of the enums code is in two classes: Flags and Enums. Both are non-generic: the methods within them are generic methods, so they have type parameters (and constraint ...
by skeet via Jon Skeet: Coding Blog on 9/10/2009 8:09:00 PM
As most readers probably know, C# prohibits generic type constraints from referring to System.Object, System.Enum, System.Array, System.Delegate and System.ValueType. In other words, this method declaration is illegal: public static T[]GetValues<T>() where T : struct, System.Enum{ return (T[]) Enum.GetValues(typeof(T)); } This is a pity, as such a method could be useful. (In fact there are better things we can do... such as returning a read-only collection. ...
by skeet via Jon Skeet: Coding Blog on 9/3/2009 11:08:00 PM
It's been a little while since I've blogged, and quite a lot has been going on. In fact, there are a few things I'd have blogged about already if it weren't for "things" getting in the way. Rather than writing a whole series of very short blog posts, I thought I'd wrap them all up here... C# in Depth: next MEAP drop available soon - Code Contracts Thanks to everyone who gave feedback on my writing dilemma. For the moment, the plan is to have a whole chapter about Co ...
by skeet via Jon Skeet: Coding Blog on 8/20/2009 4:57:40 PM
This morning I showed my hand a little on Twitter. I've had a dream for a long time about the ultimate C# book. It's a dream based on Effective Java, which is my favourite Java book, along with my experiences of writing C# in Depth. Effective Java is written by Josh Bloch, who is an absolute giant in the Java world... and that's both the problem and the opportunity. There's no-one of quite the equivalent stature in the .NET world. Instead, there are many very smart people, a lot ...
by skeet via Jon Skeet: Coding Blog on 8/5/2009 4:16:15 PM
I'd like some feedback from readers, and I suspect my blog is the simplest way to get it. I'm currently writing chapter 15 of C# in Depth, tentatively about Code Contracts and Parallel Extensions. The problem is that I'm 15 pages in, and I haven't finished Code Contracts yet. I suspect that with a typesetter moving the listings around a little it can be shortened a little bit, but I'm still concerned. With the amount I've still got to write, Code Contracts is going to en ...
by skeet via Jon Skeet: Coding Blog on 7/13/2009 4:10:00 PM
(Note that this kind of breakage was mentioned a long time ago in Eric Lippert's blog, although not in this exact form.) Whenever a conversion becomes available where it wasn't before, overload resolution can change its behaviour. From C# 1 to C# 2 this happened due to delegate variance with method group conversions - now the same thing is true for generic variance for interfaces. What does the following code print? using System; using System.Collections.Generic; class B ...
by skeet via Jon Skeet: Coding Blog on 7/7/2009 10:28:46 PM
C# 4 has some great features to make programming against COM components bearable fun and exciting. In particular: PIA linking allows you to embed just the relevant bits of the Primary Interop Assembly into your own assembly, so the PIA isn't actually required at execution time Named arguments and optional parameters make life much simpler for APIs like Office which are full of methods with gazillions of parameters "ref" removal allows you to pass an argument by value ev ...
by skeet via Jon Skeet: Coding Blog on 7/3/2009 10:28:26 PM
At a glance, this code doesn't look particularly evil. What does it do though? Compile it with the C# 4.0b1 compiler and run it... using System; class Base { public virtual void Foo(int x, int y) { Console.WriteLine("Base: x={0}, y={1}", x, y); } } class Derived : Base { public override void Foo(i ...
by skeet via Jon Skeet: Coding Blog on 6/19/2009 4:50:00 PM
Last night I presented for the first time at the Google Open Source Jam at our offices in London. The room was packed, but only a very few attendees were C# developers. I know that C# isn't the most popular language on the Open Source scene, but I was still surprised there weren't more people using C# for their jobs and hacking on Ruby/Python/etc at night. All the talks at OSJam are just 5 minutes long, with 2 minutes for questions. I'm really not used to this format, and felt extrem ...
by skeet via Jon Skeet: Coding Blog on 6/17/2009 8:01:13 PM
There have been mutterings about the fact that I haven't been blogging much recently. I've been getting down to serious work on the second edition of C# in Depth, and it's taking a lot of my time. However, I thought I'd share a ghastly little example I've just come up with. I've been having an email discussion with Sam Ng, Chris Burrows and Eric Lippert about how dynamic typing works. Sam mentioned that even for dynamically bound calls, type inference can fail at compile ...
by skeet via Jon Skeet: Coding Blog on 3/16/2009 5:21:00 PM
Update (19th March 2009) Debate around this review is getting heated. I stand by all the points I make about the text, but I'd like to clarify a few things: If there are any ad hominem comments in the review against the author, please ignore them. I'm going to try to weed out any that I find, but if you spot one, please let me know and then ignore it. I feel very strongly that a review should be about the text of a book, not about its author. The text is what will inform the r ...
by skeet via Jon Skeet: Coding Blog on 2/27/2009 11:29:00 AM
T.S. Eliot had the right idea when he wrote "The naming of cats": The Naming of Cats is a difficult matter,It isn't just one of your holiday games...When you notice a cat in profound meditation,The reason, I tell you, is always the same:His mind is engaged in a rapt contemplationOf the thought, of the thought, of the thought of his name:His ineffable effableEffanineffableDeep and inscrutable singular Name. Okay, so developers may not contemplate their own names much, but I know I ...
by skeet via Jon Skeet: Coding Blog on 1/29/2009 11:08:02 PM
As promised earlier in the week, here are the results of benchmarking for and foreach. For each of int and double, I created an array and a List<T>, filled it with random data (the same for the list as the array) and ran each of the following ways of summing the collection: A simple for loop, testing the index against the array length / list count each time A for loop with an initial variable remembering the length of the array, then comparing the index against the variable each time A ...
by skeet via Jon Skeet: Coding Blog on 1/26/2009 8:57:55 PM
While I was answering a Stack Overflow question on the performance implications of using a for loop instead of a foreach loop (or vice versa) I promised to blog about the results - particularly as I was getting different results to some other posters. On Saturday I started writing the bigger benchmark (which I will post about in the fullness of time) and used a technique that I'd used when answering a different question: have a single timing method and pass it a delegate, expected input and ...
by skeet via Jon Skeet: Coding Blog on 1/23/2009 11:40:39 PM
I've started a small project (I'll post a link when I've actually got something worthwhile to show) with some extra LINQ operators in - things which I think are missing from LINQ to Objects, basically. (I hope to include many of the ideas from an earlier blog post.) That, and a few Stack Overflow questions where I've effectively written extra LINQ operators and compared them with other solutions, have made me think about the desirable properties of a LINQ operator - or at least t ...
by skeet via Jon Skeet: Coding Blog on 1/23/2009 9:42:52 PM
This Stack Overflow question has reminded me of something I often wish existed in common exception constructors - an overload taking a format string and values. For instance, it would be really nice to be able to write: throw new IOException("Expected to read {0} bytes but only {1} were available", requiredSize, bytesRead); Of course, with no way of explic ...
by skeet via Jon Skeet: Coding Blog on 1/9/2009 7:52:14 AM
One of the reasons I don't view anonymous types as being too bad is that they're nicely confined to methods. You can't declare the type that you're returning from a method if it's anonymous (or if one of its type arguments is generic, e.g. a List<T> where T is an anonymous type and T isn't a type parameter to the method itself). However, you can get around this if you're sneaky. I've always known that it's perfectly easy to return an instance of an anony ...
by skeet via Jon Skeet: Coding Blog on 1/7/2009 5:32:24 PM
LINQ is clearly gaining a fair amount of traction, given the number of posts I see about it on Stack Overflow. However, I've noticed an interesting piece of coding style: a lot of developers are using query expressions for every bit of LINQ they write, however trivial. Now, don't get the wrong idea - I love query expressions as a helpful piece of syntactic sugar. For instance, I'd always pick the query expression form over the "dot notation" form for something like this: va ...
by skeet via Jon Skeet: Coding Blog on 12/10/2008 5:55:40 PM
There have been a couple of questions on StackOverflow about value types and parameterless constructors: Structure vs Class in C# Why can’t I define a default constructor for a struct in .NET I learned quite a bit when answering both of these. When a further question about the default value of a type (particularly with respect to generics) came up, I thought it would be worth delving into a bit more depth. Very little of this is actually relevant most of the time, but it's interesting none ...
by skeet via Jon Skeet: Coding Blog on 12/5/2008 5:52:44 PM
I've had quite a few discussions with a colleague about some failures of Java and .NET. The issue we keep coming back to is the root of the inheritance tree. There's no doubt in my mind that having a tree with a single top-level class is a good thing, but it's grown a bit too big for its boots. Pretty much everything in this post applies to both .NET and Java, sometimes with a few small changes. Where it might be unclear, I'll point out the changes explicitly - otherwise I'll ...
by skeet via Jon Skeet: Coding Blog on 12/4/2008 10:28:38 PM
I think I've now done enough public speaking to make it worth having a page with resources etc, so I've added it to the C# in Depth site. Where feasible, it will include slides, code and videos (and anything else suitable, really) from various events. I haven't got any more booked at the moment, although I've had a couple of invitations I really ought to sort out at some point. A couple of points of interest: I've included "before, during and after" code for the &q ...
by skeet via Jon Skeet: Coding Blog on 11/23/2008 10:25:53 AM
Those of you who've read C# in Depth will know about Snippy - a little tool which makes it easy to build complete programs from small snippets of code. I'm delighted to say that reader Jason Haley has taken the source code for Snippy and built an add-in for Reflector. This will make it much simpler to answer questions like this one about struct initialization, where you really want to the IL generated for a snippet. Here's a screenshot to show what it does: This is really cool - if ...
by skeet via Jon Skeet: Coding Blog on 11/19/2008 7:17:31 AM
The videos from my one day talk about C# in Copenhagen are now on the MSDN community site. There are eight sessions, varying between about 25 minutes and 50 minutes in length. I haven't had time to watch them yet, but when I do I'll submit brief summaries so you can quickly get to the bits you're most interested in. (As far as I'm aware, they're only available via Silverlight, which I realise isn't going to be convenient for everyone.) Feedback is very welcome. ...
by skeet via Jon Skeet: Coding Blog on 11/6/2008 1:38:00 AM
Update: As Chris Nahr pointed out, there's a blog post by Melitta Andersen of the BCL team explaining this in more detail. Obviously I've been looking at the proposed C# 4.0 features pretty carefully, and I promise I'll blog more about them at some later date - but yesterday I watched a PDC video which blew me away. As ever, a new version of .NET means more than just language changes - Justin van Patten has written an excellent blog post about what to expect in the core of thee frame ...
by skeet via Jon Skeet: Coding Blog on 10/30/2008 10:04:10 PM
I've not played with the VS2010 CTP much yet, and I've only looked briefly at the documentation and blogs about the new C# 4.0 dynamic type, but a thought occurred to me: why not have the option of making it generic as a way of saying "I will dynamically support this set of operations"? As an example of what I mean, suppose you have an interface IMessageRouter like this: public interface IMessageRouter{ void Send(string message, string destination);} (Th ...
by skeet via Jon Skeet: Coding Blog on 10/23/2008 8:50:39 PM
A few questions on Stack Overflow have suggested to me that there might be some bits missing from LINQ to Objects. There's the idea of a "zip" operator, which pairs up two sequences, for instance. Or the ability to apply the set operators with projections, e.g. DistinctBy, IntersectBy etc (mirroring OrderBy). They're easy to implement, but it would be nice to get a list of what people would like to see. So, what's missing? ...
by skeet via Jon Skeet: Coding Blog on 10/8/2008 8:24:09 PM
A question came up on Stack Overflow yesterday which I've had to deal with myself before now. There are times when it's helpful to have one value per type, and that value should be an instance of that type. To express it in pseudo-code, you want an IDictionary<typeof(T), T> except with T varying across all possible types. Indeed, this came up in Protocol Buffers at least once, I believe. .NET generics don't have any way of expressing this, and you end up with boxing and a cast. ...
by skeet via Jon Skeet: Coding Blog on 10/8/2008 7:42:02 PM
I'm currently reading the (generally excellent) CLR via C#, and I've recently hit the section on boxing. Why is it that authors feel they have to scaremonger about the effects boxing can have on performance? Here's a piece of code from the book: using System;public sealed class Program { public static void Main() { Int32 v = 5; // Create an unboxed value type variable.#if INEFFICIENT &nbs ...
by skeet via Jon Skeet: Coding Blog on 10/6/2008 8:51:08 PM
I suspect this has been done several times before, but on my way home this evening I considered what would be needed for the reverse of nullable value types - non-nullable reference types. I've had a play with an initial implementation in MiscUtil (not in the currently released version) and it basically boils down (after removing comments, equality etc) to this: public struct NonNullable<T> where T : class{ private readonly T value; public ...
by skeet via Jon Skeet: Coding Blog on 10/6/2008 10:45:00 AM
A while ago I wrote an article about StringBuilder and a reader mailed me to ask about the efficiency of using String.Format instead. This reminded me of a bone I have to pick with the BCL. Whenever we make a call to String.Format, it has to parse the format string. That doesn't sound too bad, but string formatting can be used a heck of a lot - and the format is almost always hard-coded in some way. It may be loaded from a resource file instead of being embedded directly in the source code, ...
by via Jon Skeet: Coding Blog on 9/9/2008 7:18:45 AM
I'm currently reading Pro LINQ: Language Integrated Query in C# 2008 by Joe Rattz and yesterday I came across a claim about Enumerable.Intersect which didn't quite ring true. I consulted MSDN and the documentation is exactly the same as the book. Here's what it says: When the object returned by this method is enumerated, Intersect enumerates first, collecting all distinct elements of that sequence. It then enumerates second, marking those elements that occur in both sequences. Final ...
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.