.NET, C#, Tips

IEnumerable to Comma Delimited String

A few years ago I blogged about how to take a delimited string and convert it to a IEnumerable.  Today we ran across the opposite of this in that we wanted to take a list and convert it to a delimited string.   This can come in handy for a number of situations so it’s worth taking a look.


List<int> values = new List<int> {10, 20, 25};

In older versions of .NET (prior to 4.0 I believe) the easiest way was to do something like the following:

string newString = string.Join(",", values.ToArray());

However, starting in 4.0, the Join has some additional overloads that make this just crazy simple:

string newString = string.Join(",", values);

If you have a list of strings, there is still some benefit to converting this to an array. There is another overload of Join that allows you to be more selective in what you are converting.

Given a list of strings like the following:

List<string> strings = new List<string> {"a", "b", "c", "d", "e", "f"};

We can look at the last overload of; String.Join(delimiter, string[], startIndex, count)

This gives us a delimited string, starting at the element in the array at startIndex and going for the number of count.

string delimited = string.Join(",", strings.ToArray(), 2, 2);

will return “c,d”

I love how the framework provides these methods, often with multiple overloads to give us a lot of power with very little code. Enjoy!

.NET, Resharper

Resharper – Navigate to Type Goodness

In my opinion the navigation improvements made by Resharper are where much of my productivity gains come into play.  When I can quickly find and navigate around my project, I can stay more focused on solving the problem at hand rather than trying to fumble through my project structure remembering where things are.

One of my favorites lately is Go To Type of Symbol (Ctrl-Shift-T in Resharper keymap, Ctrl-Shift-F11 in the Visual Studio keymap).  At it’s simplest, put your cursor on a variable and hit the keystroke.


If there is only one match, it simply takes you to the definition of the type (in your source or object browser if not).  Simple, but quick and easy.

The fun begins when there is more than one type.   The handiest example of that is when I have a List<> variable.   Then the Go To Type brings up not only the IList<> ( which I realize may be of limited usage), but it also brings up the type in the list (which is normally what I want to get at).


This get’s me quickly to what I’m looking for.

One more shortcut in my arsenal to move me quickly around my project.  Enjoy!

.NET, Code

String.Contains looking for an empty string

Here’s another one of those little idiosyncrasies that I run across in coding.  In some ways I’m almost embarrassed to say I never knew this as it’s really quite simple and also well documented, but it’s one of those edge cases that just don’t happen that often and may not be that damaging of a bug if it does sneak through.

The construct I’m talking about is the String.Contains() method.   In .NET it simply returns a true/false on whether the string contains the string parameter passed into it.

string s1 = "This is a nice string";
bool b;
b = s1.Contains("nice"); // returns true;
b = s2.Contains("bad"); // returns false;

All nice and simple. The issue I ran into was when the string I was looking for was an empty string.

b = s1.Contains(""); // returns true

In my application, that requirements were that it should return false. However, this returns true. It is well documented, but not something I really had to deal with before.

Something to keep an eye out for as it could give you some false positives if you’re not careful.

Still learning after all these years.

.NET, C#, Code, PetaPoco

PetaPoco Needs a Parameterless Constructor

I’ve been using PetaPoco for a few years as my micro-orm of choice.  It’s lightweight, simple to use, yet powerful enough for most of my needs.  Let me share one thing that I tend to forget and it seems to trip me up all the time.

In short, PetaPoco requires a parameterless constructor on the classes it’s trying to integrate with.

  public class Customer 
    public Customer() 

Or if there is no other constructor defined, the compiler will create that default constructor for you essentially and you don’t have to explicitly code it. This is where I usually run into trouble. I’ll depend on the compiler to give me the default constructor and code as follows.

  public class Customer 
    public string Name {get;set;}
    public string Address {get;set;}
    // more properties and methods

With this PetaPoco works flawlessly. No problems here. Now let’s say I create a constructor for one reason or another. For example, we want to pass the customer’s name in the constructor.

  public class Customer 
    public string Name {get;set;}
    public string Address {get;set;}

    public Customer(string _name)
      Name = _name;
    // more properties and methods

Now if we try to read in a list of customers with PetaPoco, we suddenly get a Null argument exception and it comes from deep inside PetaPoco where it’s not at first obvious what is going on. In fact, every time I get this error, I forget that I’ve seen it before and scratch my head for a few minutes…..thus this post…hopefully I’ll remember now.

Anyway, PetaPoco needs that parameterless constructor, which if we have no other constructor defined, will happily get created by the compiler. However, if we do provide a constructor like in the last example above, the compiler does not create that default constructor and we have to define it explicitly.

  public class Customer 
    public string Name {get;set;}
    public string Address {get;set;}

    public Customer() 

    public Customer(string _name)
      Name = _name;
    // more properties and methods

Once we do that, PetaPoco works beautifully once more.

.NET, Code

VB.NET, Inline If statement

I’m much more of a C# guy than VB.net .  I haven’t worked steady in VB.net since 1.1 (around 10 years or so).  However before .NET, I was a VB4-6 guy and spent many hours working in classic VB.  Having originally come from a C background, the switch to C# was natural.  One thing that had always bothered me about VB was the lack of short circuit evaluation.  I won’t explain that here, but if you want to learn more, follow that last link.  C and it’s derivatives offered it, while VB did not. 

Not a huge deal, but it often lead to some nested IF’s if you handled it, or some unsuspecting bugs if you didn’t.  Recently, I’ve been working on a project for a client that has requested the project be done in VB.net.  While working on some code, I ran across an old friend, the IIF function.

IIf(PrinterDevice Is Nothing, “<Device not setup yet>”, PrinterDevice.ToString())

Basically, just want to print “<Device not setup yet>” if the PrinterDevice object is nothing, otherwise printout the results of the ToString() on the PrinterDevice.  The problem is, if PrinterDevice is nothing, then the PrinterDevice.ToString() gives a nullreference exception.  As I was preparing to nest my If statements, I discovered something new was added to .NET 2.0 that I hadn’t run across.  For you VB guys, you’ve probably seen this already, but interestingly enough, I had not.

If(PrinterDevice Is Nothing, “<Device not setup yet>”, PrinterDevice.ToString())

That simple change (notice the IF vs IIF) makes the difference.  The IIF call is a method call, so all parameters are evaluated before the call is made.  In the case of the IF, the IF() is a statement, so it first evaluates the condition (PrinterDevice Is Nothing) and if it’s true, it prints “Device not setup yet” and never evaluates the ToString().  It performs the short circuiting that I’m used to.

Nothing new for you VB guys, but for use C# guys that are stepping into the VB world from time to time, this is a nice change.



.NET, Code, Infragistics, WinGrid

Infragistics WinGrid – Tips and Tricks #1 – Right Click Row Select

I’ve been working with Infragistics tools, specifically the UltraWinGrid for 10 years or more (worked with the Sheridan grid before that, anyone remember those tools?), and outside of the Infragistics forums there seems to be very little in the way of information on this very powerful and complex tool.  Perhaps I can leverage my experiences with these tools into a nice little series of posts on things I’ve discovered over the years.

I came upon a situation where I wanted to right click on a grid, have it select the row under the mouse and bring up a context menu to act on that selected row.  As another requirement I wanted it to only act upon data rows.

I came up with the following extension method.

  1. First get the element under the mouse and determine if it’s a row element.
  2. If it’s a row, is it a datarow?
  3. Make it the active row.
  4. if the row is not already selected, select it and deselect any other row.
  5. if the row is already selected, then do nothing else special with the selection properties.
  6. if we’ve clicked somewhere not a datarow, I clear any selected rows in the grid.
21 public static void RightClickRowSelect(thisUltraGrid grid, Point mouseLocation)  
22 {  
23     UIElement element = grid.DisplayLayout.UIElement.ElementFromPoint(mouseLocation);  
24     var row = element.GetContext(typeof(UltraGridRow)) asUltraGridRow;  
25     if (row != null && row.IsDataRow)  
26     {  
27         grid.ActiveRow = row;  
28         if (!row.Selected)  
29         {  
30            grid.Selected.Rows.Clear();  
31            row.Selected = true;  
32         }  
33     }  
34     else  
35     {   
36        grid.Selected.Rows.Clear();  
37     }  
38  }

Then to use this, I simply call it in the MouseDown event on the grid as follows.

    1     privatevoid grdLabsMouseDown(object sender, MouseEventArgs e)
    2     {
    3       if (e.Button == MouseButtons.Right)
    4       {
    5         grdLabs.RightClickRowSelect(e.Location);
    6       }
    7    }

Pretty basic really, but knowing how to determine what element is under the mouse is a critical tool in your belt when dealing with the WinGrid and opens up the door for a lot of advanced features.

.NET, Code

ActiveControl to tell me the control gaining focus.

I ran into a situation where I needed to know what control was gaining focus in the Leave() event of another control.  The situation I was working with is as follows;  I have a multi-line text box that when it gains focus I want a listview of potential values to popup below it.  When the textbox loses focus, the listview should be hidden.   The user should be able to click on the listview to select items to input into the textbox.  The problem was when the user clicked on the listview, the textbox lost focus and was hiding the listview.

Enter the ActiveControl property on the form.  This handy property allows me to check, in the Leave() event, what is the new active control with focus.  Thus I can check to see if the textbox lost the focus to the listview control and if so, skip the hiding of it.

Here we have the textbox named txtComplaint, when it gets the focus we make listView visible.

private void txtComplaint_Enter(object sender, System.EventArgs e)
  listView.Visible = true;

When the textbox loses focus we see if the ActiveControl is the listView, if not we hide it.

private void txtComplaint_Leave(object sender, System.EventArgs e)
  if (ActiveControl.Name != "listView")
    treeComplaint.Visible = false;