How to automatically insert optional curly braces in C#? - c#

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

Related

How does Visual Studio syntax-highlight strings in the Regex constructor?

Hi fellow programmers and nerds!
When creating regular expressions Visual Studio, the IDE will highlight the string if it's preceded by a verbatim identifier (for example, #"Some string). This looks something like this:
(Notice the way the string is highlighted). Most of you will have seen this by now, I'm sure.
My problem: I am using a package acquired from NuGet which deals with regular expressions, and they have a function which takes in a regular expression string, however their function doesn't have the syntax highlighting.
As you can see, this just makes reading the Regex string just a pain. I mean, it's not all-too-important, but it would make a difference if we can just have that visually-helpful highlighting to reduce the time and effort one's brain uses trying to decipher the expression, especially in a case like mine where there will be quite a quantity of these expressions.
The question
So what I'm wanting to know is, is there a way to make a function highlight the string this way*, or is it just something that's hardwired into the IDE for the specific case of the Regex c-tor? Is there some sort of annotation which can be tacked onto the function to achieve this with minimal effort, or would it be necessary to use some sort of extension?
*I have wrapped the call to AddStyle() into one of my own functions anyway, and the string will be passed as a parameter, so if any modifications need to be made to achieve the syntax-highlight, they can be made to my function. Therefore the fact that the AddStyle() function is from an external library should be irrelevant.
If it's a lot of work then it's not worth my time, somebody else is welcome to develop an extension to solve this, but if there is a way...
Important distinction
Please bear in mind I am talking about Visual Studio, NOT Visual Studio Code.
Also, if there is a way to pull the original expression string from the Regex, I might do it that way, since performance isn't a huge concern here as this is a once-on-startup thing, however I would prefer not to do it that way. I don't actually need the Regex object.
According to https://devblogs.microsoft.com/dotnet/visual-studio-2019-net-productivity/#regex-language-support and https://www.meziantou.net/visual-studio-tips-and-tricks-regex-editing.htm you can mark the string with a special comment to get syntax highlighting:
// language=regex
var str = #"[A-Z]\d+;
or
MyMethod(/* language=regex */ #"[A-Z]\d+);
(the comment may contain more than just this language=regex part)
The first linked blog talks about a preview, but this feature is also present in the final product.
.NET 7 introduces the new [StringSyntax(...)] attribute, which is used in .NET 7 on more than 350 string, string[], and ReadOnlySpan<char> parameters, properties, and fields to highlight to an interested tool what kind of syntax is expected to be passed or set.
https://devblogs.microsoft.com/dotnet/regular-expression-improvements-in-dotnet-7/?WT_mc_id=dotnet-35129-website&hmsr=joyk.com&utm_source=joyk.com&utm_medium=referral
So for a method argument you should just use:
void MyMethod([StringSyntax(StringSyntaxAttribute.Regex)] string regex);
Here is a video demonstrating the feature: https://youtu.be/Y2YOaqSAJAQ

Possible to remove/replace code in entire solution

I have multiple lines of code in my solution that I'd like to remove.
They are, in this particular scenario:
System.Diagnostics.Trace.WriteLine([STRING]);
I could've done a 'Replace All' on System.Diagnostics.Trace.WriteLine but, obviously, I want to remove the entire thing (including the string parameter passed into the method) - I want the whole line of code to be deleted wherever a call to this method is made.
Is there a way in which I can do this (any way to provide a wildcard included in the replace criteria maybe?). Also, could I do this with comments/todo's too?
I appreciate this may seem bad practice to have to get to this point but would, for now, appreciate answers that are only on topic as opposed to answers that try and propose ways of preventing this in the future (which I've already acknowledged).
You can use Regular Expression in Visual Studio Find and Replace dialog, use:
Find: ^[ \t]*(System.Diagnostics.Trace.WriteLine\(.*\)\;).*\n
Replace:
That's will delete the entire line.
You'll need to use the Regular Expression option in the Replace dialog, and something like this should do:
System.Diagnostics.Trace.WriteLine\("\w*"\);
Cheers
EDIT: Obviously, if you are passing variables to WriteLine, just remove the quotes:
System.Diagnostics.Trace.WriteLine\(\w*\);
If you mean to remove all instances of System.Diagnostics.Trace.WriteLine then you could do the following:
Go to Replace in Files dialog box
Enter System.Diagnostics.Trace.WriteLine.* in the find what box
Leave the Replace with box empty
Choose Entire Solution for Look in
Expand Find Options and tick Use and ensure Regular Expressions is shown.

ReSharper - force curly braces around single line

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

How to find the suspicious statement, like "Name = Name;" in C# by Regex?

My C# code has a lot of statement like "this.Name=...". In order to make my code neat, I let the text editor to replace all "this." to nothing. The code still worked. But later I fund it caused me a lot of new troubles for I wrote some statements like:
this.Name = Name; // the second Name is a parameter.
After the replacement, it became:
Name = Name;
Now, I met too much code. How to find the suspicious code like "Name = Name;" by Regex in VS 2010?
Thanks,
Ying
Why would you want to use Regex when you can simply compile the solution and look for the CS1717 warning:
Assignment made to same variable; did
you mean to assign something else?
Also note that in C# it is a good convention to have your parameters start with lowercase letter.
I would agree that Darin's approach is more robust and should be done first. However you might
have commented out sections of code which will be missed with this approach.
To try and find those you can use "Find in Files". In the Find box tick "Use regular expresssions" and enter {:i}:Wh*=:Wh*\1
:i C Style identifier ("tagged" expression by enclosing in braces)
:Wh* Zero or more white space chars
\1 back reference to tagged identifier found
This approach might bring back some false positives so you could try :Wh+{:i}:Wh*=:Wh*\1:Wh+ if there are too many but at the risk of missing some matches (e.g. where the closing comment mark is immediately after the assignment statement)
You could restore your last commit from your CVS, if you haven't changed too much since.
The problem with doing what you ask is that there might be other cases where "this" shouldn't have been replaced and you haven't seen the problem yet.

Any way to surround code block with Curly Braces {} in VS2008?

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

Categories

Resources