I always find myself needing to enclose a block of code in curly braces { }, but unfortunately that isn't included in the C# surround code snippets, which seems to be an oversight. I couldn't find anything on building your own surround snippets either (just other kinds of snippets).
I am actually running Resharper too, but it doesn't seem to have this functionality either (or I haven't figured how to activate it).
We have a coding standard of including even a single line of code after an if or else in curly braces, so if I could just make Resharper do that refactoring automatically that would be even better!
Here is a quick and dirty snippet to do just that.
To Install:
Save the code as SurroundWithBraces.snippet into "<my documents>\Visual Studio Version\Code Snippets\Visual C#\My Code Snippets"
To use:
Select block of text.
Press Ctrl+K, Ctrl+S
Chose My Code Snippets, braces
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>braces</Title>
<Shortcut>braces</Shortcut>
<Description>Code snippet to surround a block of code with braces</Description>
<Author>Igor Zevaka</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="csharp">
<![CDATA[{
$selected$ $end$
}]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
In ReSharper 4.5, curly braces are included as one of the built-in 'Surround Templates':
Select the text that you want curly
braces around.
ReSharper -> Code -> Surround
With... -> {}
or
ALT + R -> C -> S -> 7
or
Ctrl+E, U -> 7 (Visual Studio scheme)
or
Ctrl+Alt+J -> 7 (ReSharper 2.x/IDEA scheme)
How about:
Ctrl-X, {, Ctrl-V, }
You could even bind that to a macro.
In VS2015 there is an experimental feature that supports it by selecting the text and typing in }.
See here how to enable.
Make your own custom code snippet for doing that.
You can use snippy to create your own http://blogs.msdn.com/gusperez/articles/93681.aspx
or just use an XML editor to create one.
Put the file in My Documents\Visual Studio XXXX\Code Snippets\C#\My Code Snippets
To complete Ray Vega's answer, for those using Resharper, I figured out you can associate a shortcut to Resharper commands.
Just do the following (I am using VS 2010):
go to Tools->Options
In the listbox, extend Environment and click on Keyboard.
In the field under "Show commands containing:" enter "resharper.resharper_surroundwith"
In the field under "Press shortcut keys" enter your shortcut (eg: I choose Ctrl+R,Ctrl+S) and click Assign and then Ok.
That's it. you can select your code, and type that shorcut to view all Resharper SurroundWith commands. Just enter 7 to put braces.
Edit: This turns out to be part of DxCore, from DevExpress. Leaving here so others notice, but basically I was wrong wrong wrong. To make this particular menu go away you disable it in the 'add ins' dialog; unloading devexpress from their own menu just unloads CodeRush/Refactor, not the base support libraries.
The is (not!) a built in way to do it. I don't know if you can bind a key to it or not. Also, this embed doesn't do anything if you only select one line, so it probably won't work right if your stuff is on one line after the "if".
Select the block
Right Click
Choose "Embed Selection"
Choose "Block {}"
Note: I have DexExpress installed, but this menu is there even when it isn't loaded, and I could swear it is there even when it isn't installed. However, if I am mistaken...
This honestly seems like something that would be best to ask r# for, a user contrib perhaps?
For new comers in 2022,
Until this extension is available in the market, you have to clone the repo, build it and install it.
source
You can wrap a code block with braces by
Highlight the code block
Ctrl e -> Ctrl u
select option 7
I know this is an old question but I hope it helps someone
Ref: Wrapping multiple statements in braces
Related
When typing a function like the following:
public bool doSomething()
With the cursor at the end of the line, if I insert a { character, Visual Studio types {, inserting an extra space before the brace. I don't want the extra space. This does not appear to be an option in Text Editor -> C# -> Formatting -> Spacing. If I Ctrl+z it removes the space, so it knows it's a separate operation. I've turned off all auto-format options and it's still auto-formatting. How do I make it stop trying to be smarter than me?
Edit: I've also just discovered that when I use the keyboard shortcut to uncomment a block of code, it adds that space back in. This is also a problem.
In C# (as in Java), curly braces are optional for e.g. if blocks and loops that only contain a single statement:
if (condition) DoSomething();
I am looking for a tool that inserts missing optional curly braces for my entire solution, turning the above code into something like this:
if (condition) {
DoSomething();
}
I know that Eclipse can do this for Java. Unfortunately, I am not aware of a tool that can do this for C#. I would be grateful for suggestions! Thanks!
JetBrains Resharper gives you the possibility to do such code refactorings by a short keystroke.
You could write a ReSharper Replace Pattern.
Add a pattern to Pattern Catalog by (in ReSharper 5.1.3 ReSharper->Tools->Pattern Catalog->Add Pattern).
Then you write your pattern like so:
Unfortunatly this does not work for if-else. So you need another pattern like so:
Then you can set pattern's severity in Pattern Catalog dialog and can click Search now.
With ReSharper, go to ReSharper | Options -> Code Editing | C# | Formatting Style | Braces Layout and change neccessary options in Force Braces section to Add braces. Then find your solution in Solution Explorer, invoke context menu and choose Cleanup code... from it. Select Default: Reformat code and press Run. But be carefull! It would also reformat all code files in your solution. Be sure to backup if you do it the first time, just in case you wouldn't like ReSharper's default formatting. Maybe you would need to play with formatter settings to make it suit you.
you can use Brace Completer
http://visualstudiogallery.msdn.microsoft.com/0e33cb22-d4ac-4f5a-902f-aff5177cc94d
Is there a way to create a 'surround with' snippet in visual studio 2010? I know how to create a replacement type of snippet. A simple surround with snippet could surround a block of text with an asp:hyperlink. Similar to the way the default 'surround with' snippets can surround a block of code with an asp:panel.
It turns out that there are some pre-defined ID's that are not well documented. Specifically For SurroundWith type snippets, there is an ID $selected$. So, for example, the code for the #if snippet is:
...
<Code Language="csharp">
<![CDATA[#if $expression$ $selected$ $end$ #endif]]>
</Code>
...
The $end$ ID indicates where to place the cursor when the Surround function is complete.
That's really all there is to it. Of course, remember to include SurroundsWith as the SnippetType
For more examples, try taking a look at the predefined snippets in C:\Program Files\Microsoft Visual Studio 10.0\\Snippets\1033\.
Have a look at the MSDN article on creating snippets. It should give you a good start. When you create your snippet, be sure to give it a SnippetType of SurroundsWith to make the snippet surround selected code.
For the latest Visual Studio (currently 2017), there's Code Snippets on Microsoft Docs, as well as Walkthrough: Creating a Code Snippet.
An Example and some advice (based on the previous answers) for VS2017:
The example is for an XML snippet but I'm guessing that this will apply more or less to any language.
Paste the code below into a file and save anywhere as example.snippet
from VS do Tools->Code Snippet Manager, select Language of XML and then My XML Snippets
Click Import and select the example.snippet.
Click Finish and OK
At this point I restarted VS but such draconian measures might not be requred.
In an XML file select the text you want to surround with para tags.
Ctrl+K, Ctrl+S, select My XML Snippets and then "Example of a SurroundWith Snippet".
A <para> tag will be placed before your text and </para> after.
If you include a trailing new line then you get an extra blank line after the text and the text following the end tag appears on the same line as the end tag. It makes sense if you think about it.
If you select only part of the text on a line then you may or may not get what you are expecting. The snippet might need tweaking.
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets
xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Example of a SurroundsWith snippet</Title>
<Shortcut>shortcutsdontwork</Shortcut>
<Description>
complete example of SurroundsWith
will put para tag on the line above selected text
and /para end tag on the line below selected text
will positon the cursor immediately after the
closing angle bracket of the end tag
</Description>
<Author>mikedamay - TheDisappointedProgrammer</Author>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="XML">
<![CDATA[<para>
$selected$
</para>$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
I will restrict my editorial comments about the behaviour of code snippets in VS2017 to saying that the implementation is unusual for the modern Microsoft tools team. In particular beware of claims about what shortcuts do. As far as I can see they do nothing useful.
Appart from useful answers above, here is Code Snippets Schema Reference, which is useful for figuring out valid values for snippets elements.
Can I configure ReSharper to fix C# code when curly braces are not used to surround a single-line code block, like this:
if (blnSomeCondition)
DoSomething(); // complain
if (blnSomeOtherCondition)
{
DoSomethingElse(); // don't complain
}
Thanks
In the new version of ReSharper (2016.x) is has been moved to the Code Style.
UPD1: for ReSharper 2017.x
UPD2: for ReSharper 2018.x
UPD3: for ReSharper 2019.x
UPD4: for ReSharper 2020.x
Ryan is correct (note however that the his link refers to R# 2.0 help). The specific procedure is as follows:
Go to ReSharper > Options > Languages > C# > Formatting Style > Braces Layout
Set "Braces in "if-else" statement" to "Use braces for multiline"
After saving the changes, select a scope to reformat (could be a code selection, file, folder, project, solution - anything you want).
Choose ReSharper > Tools > Cleanup Code.
Profit.
Remember that Code Cleanup does numerous things and they're not only related to code formatting (see details at http://www.jetbrains.com/resharper/webhelp/Code_Cleanup__Index.html), so use the feature wisely.
Gorohoroh's solution is close, but instead of selecting "Use braces for multiline" I had to select "Add braces" to force it to add the braces in the single-line scenario. And I had to set that in all six dropdowns under "Force Braces" to catch all the scenarios:
What I was really hoping for was to be able to set up ReSharper to do a yellow warning or red error when the rule was violated, but I haven't found a way to do that. Because you're right, Gorohoroh, Cleanup Code does a lot of stuff and I'd like to have the option to look at and fix the rule violations one at a time.
Thanks for your help!
For ReSharper 2016.2.2.
You should edit your profile for cleaning up. The proper item is called Add/Remove braces for single statements in "if-else", "for", "foreach", "while", "do-while", "using". This item can be found within the C# => Code styles item.
If the item is checked, braces will be added; if unchecked, braces will be removed.
Note: adding doesn't work now (don't know why - perhaps, too fresh version of ReSharper). However, if you will uncheck the mentioned item, the existent braces around single statements will not be removed.
UPD: The problem solved, see the first two comments under this post.
You can configure it as seen on the screenshot.
PS: for the ones to have problem seeing Imgur.com urls -> https://ibb.co/b4xijT
Just if it can help somebody else to save time, on one machine of my company, following Sergey advices was not enough despite the great quality of his post.
On concerned setup (VS2017, R# 2019, both up to date) these settings on R# side were already good, but I also had to modify it in Visual Studio options :
In Options window, go to Text editor -> C# -> Code style ->
Formatting -> General,
Check "Perform Additional code cleanup
during formatting" and "Add/remove braces for single-line control
statement"
Well it is moved again. The new place is under the Syntax Style on version ReSharper 2020.01.
Go to ReSharper > Options > Code Editing > C# > Syntax Style > Braces
Here is the screen shot from ReSharper 2020.01
I have researched this for a few hours and I am kind of frustrated. Maybe I am just missing something as I am new to blogging.
I am not hosting my own blog, I am just using WordPress.com.
I want to include snippets of c# code and have them look like they do in Visual Studio, or at least make them look nice, certainly with line numbers and color.
The solutions I have seen for this all seem to assume you are hosting your own blog.
I cannot figure out how to install plugins.
Is there a widget that will make code snippets look nice, or some other solution I can easily use?
Thank you
EDIT: Sarfraz has outlined one way to solve my problem (thank you!), and I have tried it but there is an issue I have, namely that it does not colorize most of my code (newer keywords like var, from, where, select, etc). Is there a fix to this or is there some other solution?
Just edit your aricles in html mode and enclose your code within these tags.
[sourcecode language="css"]
[/sourcecode]
Example:
[sourcecode language="javascript"]
// javascript hello world program
alert('Hello, World !!');
[/sourcecode]
Note: You need to specify correct language identifier for the language attribute as shown above.
More Information Here :)
The [sourcecode] tag usually works fine for C#, but for me it often breaks when I post XAML code.
Instead I use this page to format my code. The result looks nice (you can see it on my blog), but it requires the "Custom CSS" option ($15/year).
EDIT: actually the [sourcecode] tag works fine, and I'm now using it in all my posts
[code language="csharp"]
//Your code here
[/code]
looks like this has been updated, now you can use
[code language="[the lang you are posting]"]
your code here
[/code]
note: you can shorthand language as lang
[code lang="[the lang you are posting]"]
your code here
[/code]
here is the list of supported languages