Visual Studio 2015 'use var' refactoring shortcut - c#

Is there a shortcut for refactoring a line of code to use the var keyword similar to what ReSharper offers?
For example if you have the following piece of code:
public void Foo()
{
List<Tuple<int, object>> bar = new List<Tuple<int, object>>();
}
ReSharper can format it into:
public void Foo()
{
var bar = new List<Tuple<int, object>>();
}

Visual Studio does not have a direct equivalent to many of the ReSharper's refactoring tools. Unfortunately, "use var" is one of the missing refactoring features, at least as of VS 2015.
You can use this regex as poor man's refactoring. Press Ctrl+H, then type
Search: (^\s*)\S[^=()]* (\w+\s*=)
Replace: $1var $2
The "\S[^=()]* " portion, including the space, matches the declaration, the ^\s* matches indentation, and \w+\s*= matches variable name and = in front of initialization.
Indentation is captured into $1 group; variable and = are captured into $2. Replacement string uses the two captured strings to format a replacement with var in the middle.
This trick can help you convert the entire file pretty quickly: visually confirm that you want to apply "refactoring" to the selected item, then press → button to go to the next declaration.
Although this approach lends itself to making a macro with relative ease, built-in support for macros has been dropped from Visual Studio as of VS 2010, so creating a quick shortcut manually for this type of refactoring would require installation of an external macro tool as well.

While there is no direct way to do this now, support for this in Visual Studio appears to be on the way in a future release of Rosalyn.
In addition to #dasblinkenlight's answer, I would keep an eye out for any custom NuGet code analyzers that do this. If it shows up as a green-squiggly error, you can effectivly get your shortcut via a quick action: Ctrl+..
I haven't been able to find one yet (besides one that does exactly the opposite of what you're looking for).

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

Visual Studio Find and Replace change casing

I'm working in a group that's converting an old WinForms app to a WPF app, using the MVVM pattern. Thus, we're having to write a lot of large models. I thought I'd write a find-and-replace regex so we can write our private variables:
private string myString;
and do a find-and-replace across the large file and get:
private string myString;
public string MyString
{
get { return myString; }
set { SetProperty("MyString", ref myString, value); }
}
this isn't too bad, the only issue I have is converting myString to MyString.
Is there a way, using straight regex capture groups, to replace a character with it's uppercase version, within Visual Studio's find-and-replace? All my searches just turn up using C# code to do the conversion, which obviously isn't possible in this context.
When I come across this issue, the sometimes fastest way is to replace everything with something completely different at first like "MyNOTString", and then back to "MyString" to get the right capital letters. It does not seem that you can get what you are asking for in Visual Studio without using Macros and such.
Another solution would be to open all the project files in a different tool like Notepad++, which supports writing /U to turn something into uppercase. See this answer.

Getting constant error indications instead of Intellisense help in LINQ query

I'm not new to Visual Studio, but I'm new to VS2012 and LINQ. As I try to build a query, instead of getting useful help from Intellisense with table field names, all I get is a look-ahead and errors indicated on the next lines of code. Let's say I have two lines of code. When I try to insert a line in between, VS is doing red underlines on the new line 3, because line 2 is still incomplete as I'm typing it out.
This is just a simple Console app that I'm working on as I learn this stuff. I have a "using System.Linq" in the file.
Notice in my example screenshot how "where", "foreach" are underlined in red as I'm typing it out. When I type the period after c, I'm expecting a list of field names to pop up.
I'm spoiled by Resharper, so Visual Studio isn't giving me the same behavior, but here are a couple of tips which may help:
Make sure you have a using System.Linq; statement. This isn't always immediately obvious because it feels like where is a keyword and shouldn't rely on a specific package, but due to the way LINQ relies on extension methods, this is necessary.
Try putting a semicolon after your LINQ statement:
var Test = from t in new[] {1, 2, 3} where t. ;
This should help avoid look-ahead problems since it's more obvious that the foreach has nothing to do with this.
Consider getting Resharper.

How to automatically insert optional curly braces in 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

"redundant comma in array initializer" why it should be fixed

With ReSharper 6.0 I've received a new warning:
redundant comma in array initializer
for the case when I have a list of array initializer parameters with comma in the end.
What bad in that? Why I like "my" approach is that I often need to comment the latest value and don't want to bother with fixing those 'leading' commas:
private readonly string[] _tables
= new[]
{
"users",
"user_account",
"user_budget_type",
//"user_budget"
};
Please advise what is good in following that suggestion.
Thank you.
I agree that it shouldn't matter that there is a comma at the end, however, if you write your arrays like so, you don't have this problem.
private readonly string[] _tables
= new[]
{
"users"
,"user_account"
,"user_budget_type"
//,"user_budget"
};
The clue is in the text of the message:
redundant comma in array initializer
What does it mean by that? Well, your code:
private readonly string[] _tables
= new[]
{
"users",
"user_account",
"user_budget_type",
//"user_budget"
};
and the code with the inspection acted upon:
private readonly string[] _tables
= new[]
{
"users",
"user_account",
"user_budget_type"
//"user_budget"
};
are semantically equivalent. That is, the CIL produced in each case is identical - there is no difference in behaviour. So the comma changes nothing and is therefore redundant.
Now, as to your question:
What bad in that?
That's largely up to you. R# merely has this redundancy as an inspection, but it is you (through your acceptance of the default settings) that has it categorised as a warning.
If this construct is acceptable to your style, then by all means go ahead and change the Inspection Severity in R# options; but in general, the defaults for R# options are those that produce pretty close to the minimum amount of code necessary.
ReSharper is full of suggestions. Just like any other productivity tool, in the end it's up to you whether to act upon those suggestions.
For example, while the C# language allows a trailing comma or an empty control statement bodies (placing a ; for a loop body), or even typing duplicate ;; at the end of the statement. For all those things ReSharper will suggest you removing redundancies, because it's what it does - heuristically detects redundancies. If you know better, there are several ways you could "silence" ReSharper from suggesting it:
Temp. suppress the warning using special comments (choose the "Suppress inspection ... with comment" quickfix):
private readonly string[] _tables = new[]
{
"users",
"user_account",
// ReSharper disable RedundantCommaInArrayInitializer
"user_budget_type",
// ReSharper restore RedundantCommaInArrayInitializer
//"user_budget"
};
or
2. Suppress this warning completely by selecting "Inspection options for ...", and choosing "Do not show" in the options.
It's all about choice and personal preference - you can configure just about anything you want in the tool.
You can suppress that warning, Resharper is just saying that, just in case you care :)
#Budda, Unlike other have said, this redundant comma is eval!
In some browsers, for example IE8, this could cause the browser to misunderstand you and mis-create the object.
See this answer for example, where the trailing comma caused the Highcharts library to stop working.
Keeping your code clean is not only a matter of easier reading and debugging. Even if you see your code working with this comma, it doesn't mean that it will be working the same with all browsers.

Categories

Resources