Showing posts with label note-to-self. Show all posts
Showing posts with label note-to-self. Show all posts

Wednesday, September 10, 2014

C# – Shorten null check around foreach loops

This is another blog post filed under “So I can remember this for next time. If it helps you too, great!”

In C#, when looping over a collection where the collection object itself might be null, if the desired behavior is to just loop zero times if the collection object is null, typical code would be:

List<MyType> list = PopulateList(); // Some method that returns a List<MyType>, or null 
if (list != null) 
{ 
  foreach (MyType mt in list) 
  { 
    // Do stuff with mt... 
  }
}

Using the C# null-coalescing operator ??, the above code can be condensed to:

List<MyType> list = PopulateList(); // Some method that returns a List<MyType>, or null
foreach (MyType mt in list ?? Enumerable.Empty<MyType>) 
{ 
  // Do stuff with mt... 
}

In that second example, if list is non-null, then the foreach iterates over it as normal. If list is null, then the foreach iterates over an empty collection -- so zero iterations are performed.

Wednesday, August 06, 2014

Double-click-drag to select entire words

Here’s a quick tip on selecting text with the mouse that I’m blogging as much to help myself remember as to inform you, the reader:

You can double-click-drag – that is, double-click, and continue holding the mouse button on the 2nd click – to select multiple entire words from a block of text.  This obviates the need to position the mouse cursor exactly over the small space between words when selecting entire words or sentences, both when beginning and ending the selection.

Bonus tip: You can triple-click to select an entire line or paragraph of text.  (This one I do remember and use frequently – and get annoyed by those few applications that don’t support it.)

These tips work in most applications on both Windows and Mac.