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.
Related
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
Is there a way to make the code analysis spell-checker accept an acronym that contains a number?
I'm getting CA1704 and CA1709 warnings from code analysis in a C# application where I have identifiers with an acronym that contains a number. For example, "CheckAbc2deStatus". CA1704 wants to correct the spelling of Abc, while CA1709 wants "de" changed to "DE". I found Code analysis, Lost between CA1709 and CA1704 and have tried putting "Abc2de" in the code analysis dictionary as Words/Recognized/Word, Words/Compound/Term, and Acronyms/CasingExceptions/Acronym, but none of those entries will make the code analyzer happy. Other entries in the custom dictionary for "normal" acronyms work as expected.
I got it to work with:
Code:
public static bool CheckABC2DEStatus()
{
return true;
}
And in the Code Analysis Dictionary:
<Acronyms>
<CasingExceptions>
<Acronym>ABC</Acronym>
<Acronym>DE</Acronym>
</CasingExceptions>
</Acronyms>
The number seems to be treated as a word break, so I had to put the two halves in seperately.
If CheckABC2DEStatus isn't your preferred method name, let me know and I'll try and adjust the dictionary entry accordingly.
Valid syntax:
var test = new List<string>
{
"a",
"b",
"c",//Valid trailing comma
};
Invalid syntax:
private void Test(params string[] args)
{
}
Test(
"a",
"b",
"c",//Invalid trailing comma
);
Is it a matter of syntax inconsistency or a calculated decision?
So I'll take a stab at this even though I will never know the "true" reason as I wasn't on the compiler team - and the likelihood of one turning up is questionable.
Trailing commas are generally useful in a few scenarios, namely merging and code-generation. In the context of stuff like collection or property initialisers and enums, leaving a trailing comma is harmless (the compiler can safely infer "end of list" as there is also a closing block bracket it can hook on to.
Method parameters are quite explicit - the compiler needs a lot of control in this area so that it can provide good feedback when people are coding and for other ancillary features. Leaving a trailing comma on method arguments doesn't add any of the value as above and my start to cause confusion over how to handle "incomplete" code (did the user leave it there intentionally or are they just about to type in the next argument?).
You are correct that params fall into the conceptual gap in that you see them as an array, and you can specify them as comma delimited (which was supported prior to collection initialisers). So why do they depart in style from collection initialisers?
The language spec for the params bit doesn't explicitly specify trailing comma support, though it does for collection initialisers for parity towards other languages (C++ I think), which increases familiarity with developers migrating to C# from elsewhere.
My supposition: the fact that it wasn't in spec then causes YAGNI to apply, and from that point forwards the value proposition for the feature is a no-brainer in favour of not implementing it.
if you look at lexical Grammer here
C.2.9 Arrays
array-initializer:
{ variable-initializer-listopt }
{ variable-initializer-list , }// This comma is causing this
variable-initializer-list:
variable-initializer
variable-initializer-list , variable-initializer
Calling Function is Like this ....MethodName( formal-parameter-listopt );
formal-parameter-list:
fixed-parameters
fixed-parameters , parameter-array
parameter-array
fixed-parameters:
fixed-parameter
fixed-parameters , fixed-parameter
fixed-parameter:
attributesopt parameter-modifieropt type identifier
parameter-modifier:
ref
out
parameter-array:
attributesopt params array-type identifier
There is no place for trailing commas because, language is written that way, I don't know the reason but Adam does
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.
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.