Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to surround a code block with a using statement in ReSharper?

I'm watching Stephen A Bohlen's excellent Summer of NHibernate series, and have been watching him interact with CodeRush. I've recently installed ReSharper (I'm a ReSharper newbie), and I'm trying to find some of the ReSharper productivity equivalents that Stephen is demonstrating (tangentially) with CodeRush.

As an example, he demonstrates highlighting a code block that looks like this:

ISession session = GetSession();
session.xxx

and then turning it into

using (ISession session = GetSession())
{
   session.xxx
}

He does this by highlighting the block he wants to surround with the using statement and then invoking some CodeRush template. I've been unable to figure out how to do the equivalent thing with ReSharper. I found the ReSharper Surround command (within the Code command), but when you select the using statement, it does surround your highlighted code block, but it does not seem smart enough to put the first line within the using clause. That is, it results in:

using () 
{
  ISession session = GetSession();
  session.xxx
}            

which requires me to move the first line into the using clause. Am I missing an easier way?

like image 821
Howard Pinsley Avatar asked Dec 07 '22 08:12

Howard Pinsley


2 Answers

Resharper offers this capability. If your class implements IDisposable, just hit Alt-Enter:

(removed image dead link "Before")
(removed image dead link "After")

You also have to have your cursor on variable name. Like this: SShot1 SShot2 SShot3

like image 178
Mindaugas Mozūras Avatar answered Dec 27 '22 11:12

Mindaugas Mozūras


I was just watching that episode and wondering if I the same question. Based on the leads here, I found that if I had this code:

1        IList<Supplier> returnValue;
2        ISession session = SessionProvider.GetSession();
3        returnValue = session.CreateQuery("select from Supplier s").List<Supplier>();
4        return returnValue;

If I put my cursor on the session variable in line 2, and then did Alt-Enter, it would give me:

1        IList<Supplier> returnValue;
2        using (ISession session = SessionProvider.GetSession())
3        {
4            returnValue = session.CreateQuery("select from Supplier s").List<Supplier>();
5        }
6        return returnValue;

It did get me a couple of times because I did not have my cursor on the variable name, but I did get it to work.

Just a side note, I really prefer watching demonstrations where they are using Code Rush simply because you have visual indicators of what is going on. I wonder if that would get in the way if I was not presenting.

And you are NOT a Resharper Newbie: You are a Resharper Padawan :)

Swampy

like image 27
SwampyFox Avatar answered Dec 27 '22 11:12

SwampyFox