Adding Users Programmatically to A Claims Site in SharePoint 2010

I had a friend send me kind of an interesting problem the other day.  He was trying to add a new user programmatically to a Windows claims site and having all sorts of difficulties.  His initial attempt at adding the user with domain\username and the SPRoleAssignment class was not working for him.  He then tried various flavors of providing the claims encoded value for what the user name should be and got that to work partially, but had some strange side effects like the name appearing twice.  While I didn't have a chance to personally examine all the variations and issues he had, what I did find worked for me on the first try was just to use the EnsureUser method on SPWeb.  It's much simpler than having to fool around to try and get the encoding for an account name; it's also a lot easier because you only need to pass in the account name instead of the four parameters you normally have to use to add a user.  EnsureUser automatically takes care of encoding the name and really simplified his code. 

For completeness here's a short example:

using (SPSite theSite = new SPSite("https://foo"))
{
  using (SPWeb theWeb = theSite.OpenWeb())
  {
    SPUser theUser = theWeb.EnsureUser("domain\username");
  }
}

UPDATE:  Make sure you read this post on how you should format the user name:  https://blogs.technet.com/b/speschka/archive/2013/02/03/what-you-need-to-know-about-using-ensureuser-in-claims-based-web-apps-in-sharepoint-2010-and-sharepoint-2013.aspx.