I use VSCode for editing Unity scripts. I have just updated to VSCode 1.65.2.
Before I updated, I was able to type out a for-loop without any problems.
For instance: for(int i=0; i<10; i++) { }, however, now whenever I type the "i<" keys, VSCode auto-adds "async" to my method signature and "await" to the cursor position where I was typing. This is very annoying as I use "i" (i<) for most of my for-loops. Is there a way to disable this feature in VSCode? In addition, I am not sure what the feature is called, so I have not been able to find anything about it myself. I have searched for "Emmet", "Abbreviations", "Suggestions", "Snippets". None of these categories are producing results for me. Even searching for "i<" as a short-code has not produced any results. To be clear, I would like to disable whatever is causing "i<" from converting my method signatures and adding code. If anyone can help with this, it would be much appreciated. Thanks.
OK, finally found something that worked.
In File > Preferences > Settings I enabled Omnisharp: Enable Async Completion according to this question. This worked for me. Thank you.
using "Visual Studio Code 1.15.1";
I've been using VSCode on my Mac to view some C# code I had written elsewhere, and for some reason, certain things aren't highlighted correctly.
(0) await statements are not highlighted correctly when used with a variable instead of a method call or member accessor.
await someTask; // highlighted as if someTask were a variable of type await
await someThing.SomeTask; // highlighted correctly
await someThing.DoSomething(); // highlighted correctly
(1) using is highlighted as if it were a function instead of a keyword.
using (var spoon = new DisposableSpoon()) {
// ...
}
which didn't happen before.
(2) Some C# 7 features aren't highlighted correctly, such as out variables.
if (map.TryGetValue(key, out TValue val)) {
// ...
}
I'm using the default theme (Dark+), and I don't think I have any major, workspace-breaking plugins enabled (most are just extra themes or support for other languages). Did I accidentally mess up a config or something, or is this a bug?
Edit: (1) is fixed when I change the language from "C#" to "C# (official)". There seem to be multiple C#'s for some reason, but none seem to fix all of the aforementioned bugs. If this is just due to a wonky config or something, how would I revert to default?
The await issue seems like a bug in our built-in c# grammar. I've opened an issue with the grammar we use to track this: https://github.com/dotnet/csharp-tmLanguage/issues/83
I can only repo (1) when not within a class or method body, and I can't repo (2). Can you please file issues for these as well. Include the code, a screenshot, and a short explanation of what looks incorrect: https://github.com/dotnet/csharp-tmLanguage/issues/new
Is there a way to disable all Resharper warnings for a file or section of code with a single comment? I'm trying to create some coding exercises for interviewing potential candidates, and the Resharper warnings give away the problem I want the candidate to spot :P Suppressing the specific warning still makes it obvious what the problem is.
I still want to have Resharper available during the interview, I just want the candidate to spot this problem without Resharper spoiling the fun.
edit: Sorry I'll try to be more clear about what I'm after. I don't want to permanently disable a particular Resharper warning, I just want it to not show in one particular file, because the point of the exercise is to see if the developer understands the reason for the warning.
To give one example, there is a Resharper warning to use the .Any extension method instead of Count() > 0, which I want the developer to point out themselves. To disable that warning, you have to use a comment of:
// ReSharper disable UseMethodAny.0
around the code. That kind of gives the game away a little.
I was trying to find something like:
// ReSharper disable all
which I could place at the top of the class, so it won't give away what I want the developer to find. But I can't seem to find a way to do that. Using numbers for the Resharper warnings would be fine as well, but I don't think it works that way?
You can press Ctrl + Shift + Alt + 8 to disable analyses and highlightings in the current file.
According to this blog post on the JetBrains blog, in ReSharper 8 there will be a single comment that can disable ReSharper warnings in a file.
It will be
// ReSharper disable All
Note: The "All" is case-sensitive, the rest is not.
The following worked for me.
Add "No Resharper" to Generated Code Regions in R# -> Options -> Code Inspection -> Generated Code
Use the following to suppress the warnings:
#region No Resharper
// All R# warnings are suppressed here
#endregion
You could also use the SuppressMessageAttribute with ReSharper as the category and All as the checkId on the method or the class as shown below. This is more granular than disabling everything in the file if you need the fine grained control.
Tested with Visual Studio 2015 Update 3 and ReSharper Ultimate 10.0.2
[SuppressMessage("ReSharper", "All")]
private void MethodWithMultipleIssues()
{
TestClass instance = null;
// You would get an "Expression is always true" message
if (instance == null)
{
Debug.WriteLine("Handle null");
}
else
{
// You would get an "Code is unreachable" message
Debug.WriteLine("Handle instance");
}
}
you have to configure the ReSharper Inspections
http://www.jetbrains.com/resharper/webhelp/Code_Analysis__Configuring_Warnings.html
You can add the file to the list of "Generated Code" in ReSharpers Options Menu:
Options > CodeInspection > Generated Code
I would like (in an ELEGANT way) to use some custom method attribute which will give me this:
When I call such a method foo(), in some attribute I'll have the elapsed time (how long the method call lasted).
How can I do it in C#? Reflections?
Thank you in advance.
James
C# doesn't offer this out of the box. You have a few choices:
Use some external profiler (I think higher editions of VS have one integrated)
Use an AOP framework. For example Postsharp rewrites your IL in an after build step to introduce prolog/epilog code based on attributes.
What's wrong with the StopWatch class? I use it regularly for profiling general timings in critical code. If that's not enough, I'll switch to ANTS (or dotTrace).
Action<Action> elegantBenchmark = (body) =>
{
var startTime = DateTime.Now;
body();
Console.WriteLine(DateTime.Now - startTime);
};
elegantBenchmark(DoWork);
P.S.
PostSharp will do the work as you want it to be done.
There is no way to intercept a plain old method call in C#. You would have to post(pre)-process your C# code (like with PostSharp) to really achieve this.
Alternatively, you could write a benchmarking method that takes a lambda to time a chunk of code, but this is obviously not a true decorator.
In C# I use the #warning and #error directives,
#warning This is dirty code...
#error Fix this before everything explodes!
This way, the compiler will let me know that I still have work to do. What technique do you use to mark code so you won't forget about it?
Mark them with // TODO, // HACK or other comment tokens that will show up in the task pane in Visual Studio.
See Using the Task List.
Todo comment as well.
We've also added a special keyword NOCHECKIN, we've added a commit-hook to our source control system (very easy to do with at least cvs or svn) where it scans all files and refuses to check in the file if it finds the text NOCHECKIN anywhere.
This is very useful if you just want to test something out and be certain that it doesn't accidentaly gets checked in (passed the watchful eyes during the diff of everything thats commited to source control).
I use a combination of //TODO: //HACK: and throw new NotImplementedException(); on my methods to denote work that was not done. Also, I add bookmarks in Visual Studio on lines that are incomplete.
//TODO: Person's name - please fix this.
This is in Java, you can then look at tasks in Eclipse which will locate all references to this tag, and can group them by person so that you can assign a TODO to someone else, or only look at your own.
If I've got to drop everything in the middle of a change, then
#error finish this
If it's something I should do later, it goes into my bug tracker (which is used for all tasks).
'To do' comments are great in theory, but not so good in practice, at least in my experience. If you are going to be pulled away for long enough to need them, then they tend to get forgotten.
I favor Jon T's general strategy, but I usually do it by just plain breaking the code temporarily - I often insert a deliberately undefined method reference and let the compiler remind me about what I need to get back to:
PutTheUpdateCodeHere();
An approach that I've really liked is "Hack Bombing", as demonstrated by Oren Eini here.
try
{
//do stuff
return true;
}
catch // no idea how to prevent an exception here at the moment, this make it work for now...
{
if (DateTime.Today > new DateTime(2007, 2, 7))
throw new InvalidOperationException("fix me already!! no catching exceptions like this!");
return false;
}
Add a test in a disabled state. They show up in all the build reports.
If that doesn't work, I file a bug.
In particular, I haven't seen TODO comments ever decrease in quantity in any meaningful way. If I didn't have time to do it when I wrote the comment, I don't know why I'd have time later.
//TODO: Finish this
If you use VS you can setup your own Task Tags under Tools>Options>Environment>Task List
gvim highlights both "// XXX" and "// TODO" in yellow, which amazed me the first time I marked some code that way to remind myself to come back to it.
I'm a C++ programmer, but I imagine my technique could be easily implemented in C# or any other language for that matter:
I have a ToDo(msg) macro that expands into constructing a static object at local scope whose constructor outputs a log message. That way, the first time I execute unfinished code, I get a reminder in my log output that tells me that I can defer the task no longer.
It looks like this:
class ToDo_helper
{
public:
ToDo_helper(const std::string& msg, const char* file, int line)
{
std::string header(79, '*');
Log(LOG_WARNING) << header << '\n'
<< " TO DO:\n"
<< " Task: " << msg << '\n'
<< " File: " << file << '\n'
<< " Line: " << line << '\n'
<< header;
}
};
#define TODO_HELPER_2(X, file, line) \
static Error::ToDo_helper tdh##line(X, file, line)
#define TODO_HELPER_1(X, file, line) TODO_HELPER_2(X, file, line)
#define ToDo(X) TODO_HELPER_1(X, __FILE__, __LINE__)
... and you use it like this:
void some_unfinished_business() {
ToDo("Take care of unfinished business");
}
It's not a perfect world, and we don't always have infinite time to refactor or ponder the code.
I sometimes put //REVIEW in the code if it's something I want to come back to later. i.e. code is working, but perhaps not convinced it's the best way.
// REVIEW - RP - Is this the best way to achieve x? Could we use algorithm y?
Same goes for //REFACTOR
// REFACTOR - should pull this method up and remove near-dupe code in XYZ.cs
I use // TODO: or // HACK: as a reminder that something is unfinished with a note explaining why.
I often (read 'rarely') go back and finish those things due to time constraints.
However, when I'm looking over the code I have a record of what was left uncompleted and more importantly WHY.
One more comment I use often at the end of the day or week:
// START HERE CHRIS
^^^^^^^^^^^^^^^^^^^^
Tells me where I left off so I can minimize my bootstrap time on Monday morning.
// TODO: <explanation>
if it's something that I haven't gotten around to implementing, and don't want to forget.
// FIXME: <explanation>
if it's something that I don't think works right, and want to come back later or have other eyes look at it.
Never thought of the #error/#warning options. Those could come in handy too.
I use //FIXME: xxx for broken code, and //CHGME: xxx for code that needs attention but works (perhaps only in a limited context).
Todo Comment.
These are the three different ways I have found helpful to flag something that needs to be addressed.
Place a comment flag next to the code that needs to be looked at. Most compilers can recognize common flags and display them in an organized fashion. Usually your IDE has a watch window specifically designed for these flags. The most common comment flag is: //TODO This how you would use it:
//TODO: Fix this before it is released. This causes an access violation because it is using memory that isn't created yet.
One way to flag something that needs to be addressed before release would be to create a useless variable. Most compilers will warn you if you have a variable that isn't used. Here is how you could use this technique:
int This_Is_An_Access_Violation = 0;
IDE Bookmarks. Most products will come with a way to place a bookmark in your code for future reference. This is a good idea, except that it can only be seen by you. When you share your code most IDE's won't share your bookmarks. You can check the help file system of your IDE to see how to use it's bookmarking features.
I also use TODO: comments. I understand the criticism that they rarely actually get fixed, and that they'd be better off reported as bugs. However, I think that misses a couple points:
I use them most during heavy development, when I'm constantly refactoring and redesigning things. So I'm looking at them all the time. In situations like that, most of them actually do get addressed. Plus it's easy to do a search for TODO: to make sure I didn't miss anything.
It can be very helpful for people reading your code, to know the spots that you think were poorly written or hacked together. If I'm reading unfamiliar code, I tend to look for organizational patterns, naming conventions, consistent logic, etc.. If that consistency had to be violated one or two times for expediency, I'd rather see a note to that effect. That way I don't waste time trying to find logic where there is none.
If it's some long term technical debt, you can comment like:
// TODO: This code loan causes an annual interest rate of 7.5% developer/hour. Upfront fee as stated by the current implementation. This contract is subject of prior authorization from the DCB (Developer's Code Bank), and tariff may change without warning.
... err. I guess a TODO will do it, as long as you don't simply ignore them.
This is my list of temporary comment tags I use:
//+TODO Usual meaning.
//+H Where I was working last time.
//+T Temporary/test code.
//+B Bug.
//+P Performance issue.
To indicate different priorities, e.g.: //+B vs //+B+++
Advantages:
Easy to search-in/remove-from the code (look for //+).
Easy to filter on a priority basis, e.g.: search for //+B to find all bugs, search for //+B+++ to only get high priority ones.
Can be used with C++, C#, Java, ...
Why the //+ notation? Because the + symbol looks like a little t, for temporary.
Note: this is not a Standard recommendation, just a personal one.
As most programmers seem to do here, I use TODO comments. Additionally, I use Eclipse's task interface Mylyn. When a task is active, Mylyn remembers all resources I have opened. This way I can track
where in a file I have to do something (and what),
in which files I have to do it, and
to what task they are related.
Besides keying off the "TODO:" comment, many IDE's also key off the "TASK:" comment. Some IDE's even let you configure your own special identifier.
It is probably not a good idea to sprinkle your code base with uninformative TODOs, especially if you have multiple contributors over time. This can be quite confusing to the newcomers. However, what seems to me to work well in practice is to state the author and when the TODO was written, with a header (50 characters max) and a longer body.
Whatever you pack into the TODO comments, I'd recommend to be systematic in how you track them. For example, there is a service that examines the TODO comments in your repository based on git blame (http://www.tickgit.com).
I developed my own command-line tool to enforce the consistent style of the TODO comments using ideas from the answers here (https://github.com/mristin/opinionated-csharp-todos). It was fairly easy to integrate it into the continuous integration so that the task list is re-generated on every push to the master.
It also makes sense to have the task list separate from your IDE for situations when you discuss the TODOs in a meeting with other people, when you want to share it by email etc.