LINQPad is a very useful code snippet IDE. I use it all the time to test small pieces of code. It's much more convenient than opening a new Visual Studio console application. It also formats the results very nicely.

What seems to be missing in LINQPad is a way to add methods or classes. After digging a bit with reflector, I came up with a simple way:

  • Choose "C# Statement(s)" in the Type drop-down.
  • Write the code that LINQPad should execute.
  • Put a closing curly-bracket ("}") at the end.
  • Write as many classes and methods as you like.
  • On the last class/method, omit closing curly-bracket.

LINQPad simply compiles the code you're writing there, wrapping it in a class and a single method, which it then executes. By adding the closing bracket, we're actually ending the method it defines, and start writing our own methods and classes. Since a closing bracket will be added at the end of the code block, we omit it from our code.

If you want your classes to be proper (not inner), you will need to put two closing curly-brackets, and then define your class. This is important if you want to define extension methods (which must reside in a static, non-inner class).

Tagged with:
 

3 Responses to Writing Methods and Classes in LINQPad

  1. Simon Chadwick says:

    Many thanks for these tips. Now I can write extension methods in LINQPad, although it is rather a hack. I hope LINQPad is updated to be smarter about classes.

  2. Pascal says:

    Yes me too, thanks a lot

  3. Patrick says:

    Just to update, LINQPad now handles this by selecting “C# Program”; see http://www.linqpad.net/CodeSnippetIDE.aspx

Set your Twitter account name in your settings to use the TwitterBar Section.