I am using VS 2010 and testing something real basic :
class Program
{
static void Main(string[] args)
{
var numbers = new int[2];
numbers[3] = 0;
}
}
I have gone to properties > Code Contracts and have enabled the static checking. No errors / warnings/squiggly underlines are showing on compile / build.
EDIT:
When turning the warning level to max I get this warning, which is not the warning I am after :
Warning 1 CodeContracts: Invoking method 'Main' will always lead to an error. If this is wanted, consider adding Contract.Requires(false) to document it
It's not clear what warning you're expecting (you state "I get this warning, which is not the warning I am after" without actually saying what warning you are after), but perhaps this will help.
First up:
var numbers = new int[2];
numbers[3] = 0;
This is an out-of-bounds access that will fail at runtime. This is the cause of the error you're getting, which states that "Invoking method 'Main' will always lead to an error." - that's perfectly accurate, it will always lead to an error because that out-of-bounds array access will always throw a runtime exception.
Since you state that this isn't the warning you're expecting, though, I've had to employ a bit of guesswork as to what you were expecting. My best guess was that due to having ticked the 'Implicit Non-Null Obligations' checkbox, and also having tried adding Contract.Requires(args != null) to your code, you're expecting to get a warning that your Main method could potentially be called with a null argument.
The thing is, Code Contracts will only inspect your own code to make sure that you always provide a non-null argument when calling Main. The thing is, you never call Main at all - the operating system will call Main, and Code Contracts is not going to inspect the operating system's code!
There's no way to provide compile-time checking of the arguments provided to Main - you have to check these at runtime, manually. Again, Code Contracts works by checking that calls you make to a function meet the requirements you set - if you're not actually making the calls yourself, Code Contracts has no compile-time say in the matter.
I have tried this (albeit with Visual Studio 2013 + Code Contracts) and I found the following:
With the Warning Level set to "low" (like you have), I do not get a warning.
With the Warning Level set to "hi", I do get a warning.
So I suggest increasing your warning level slider.
Problem Description:
As a single developer I've stumbled across this several times:
Sometimes on a project instead of choosing a cleaner approach it makes sense for efficiency reasons to just add some quick and dirty test-code within production code.
While it may sound like a dirty solution, please keep in mind, that I'm only talking about test-code that should be thrown away anyway, when I just want to quickly check something.
To be 100% sure to not forget to take this code out again I'd like to guard it by a compile time timebomb:
What I mean is some piece of code, preprocessor code or anything basically that allows for compilation for a certain timespan, like half an hour for instance and then automatically results in a compiler error after the time (half an hour) is over. A compiler error would be great because it could directly mark the place of the test-code. (I could have it as the first line(s) within such a throwaway region for instance)
So anything like "throw an error if system time is bigger than this specific DateTime" would be great.
I looked into the preprocessor (not too familiar with it) but the directives #if and #error didn't seem like an option since #if expects a symbol instead of an expression.
Question:
Is such a timebomb possible? Any idea on how to do that?
Or any idea on how to get the efficiency of quick and dirty test-code and be absolutely sure that taking it out again can't be forgotten?
(A run time error would be easy but if a compile time error isn't possible I would need something of a similar quality to it.)
I personally think, that timebombing is the wrong approach. Use build targets to distinguish different purpose of code usage.
// Constructor call will only be allowed for target DEBUG
public class Protect : IDisposable
{
#if DEBUG
[Obsolete("error", false)]
#else
[Obsolete("error", true)]
#endif
public Protect()
{
}
public void Dispose()
{
}
}
Usage
using (new Protect())
{
// do some testcode
// will only compile in DEBUG mode
}
One option is to generate file that has "current time" variable at build time and than simply add check that code should stop working after particular time.
Possible approach to generate file at build time - how to put computed value in RESX at build time C#
Ok, consider the following code:
const bool trueOrFalse = false;
const object constObject = null;
void Foo()
{
if (trueOrFalse)
{
int hash = constObject.GetHashCode();
}
if (constObject != null)
{
int hash = constObject.GetHashCode();
}
}
trueOrFalse is a compile time constant and as such, the compiler warns correctly that int hash = o.GetHashCode(); is not reachable.
Also, constObject is a compile time constant and as such the compiler warns again correctly that int hash = o.GetHashCode(); is not reachable as o != null will never be true.
So why doesn't the compiler figure out that:
if (true)
{
int hash = constObject.GetHashCode();
}
is 100% sure to be a runtime exception and thus issue out a compile time error? I know this is probably a stupid corner case, but the compiler seems pretty smart reasoning about compile time constant value types, and as such, I was expecting it could also figure out this small corner case with reference types.
UPDATE: This question was the subject of my blog on July 17th 2012. Thanks for the great question!
Why doesn't the compiler figure out that my code is 100% sure to be a runtime exception and thus issue out a compile time error?
Why should the compiler make code that is guaranteed to throw into a compile-time error? Wouldn't that make:
int M()
{
throw new NotImplementedException();
}
into a compile-time error? But that's exactly the opposite of what you want it to be; you want this to be a runtime error so that the incomplete code compiles.
Now, you might say, well, dereferencing null is clearly undesirable always, whereas a "not implemented" exception is clearly desirable. So could the compiler detect just this specific situation of there being a null ref exception guaranteed to happen, and give an error?
Sure, it could. We'd just have to spend the budget on implementing a data flow analyzer that tracks when a given expression is known to be always null, and then make it a compile time error (or warning) to dereference that expression.
The questions to answer then are:
How much does that feature cost?
How much benefit does the user accrue?
Is there any other possible feature that has a better cost-to-benefit ratio, and provides more value to the user?
The answer to the first question is "rather a lot" -- code flow analyzers are expensive to design and build. The answer to the second question is "not very much" -- the number of situations in which you can prove that null is going to be dereferenced are very small. The answer to the third question has, over the last twelve years, always been "yes".
Therefore, no such feature.
Now, you might say, well, C# does have some limited ability to detect when an expression is always/never null; the nullable arithmetic analyzer uses this analysis to generate more optimal nullable arithmetic code (*), and clearly the flow analyzer uses it to determine reachability. So why not just use the already existing nullability and flow analyzer to detect when you've always dereferenced a null constant?
That would be cheap to implement, sure. But the corresponding user benefit is now tiny. How many times in real code do you initialize a constant to null, and then dereference it? It seems unlikely that anyone would actually do that.
Moreover: yes, it is always better to detect a bug at compile time instead of run time, because it is cheaper. But the bug here -- a guaranteed dereference of null -- will be caught the first time the code is tested, and subsequently fixed.
So basically the feature request here is to detect at compile time a very unlikely and obvioulsy wrong situation that will always be immediately caught and fixed the first time the code is run anyways. It is therefore not a very good candidate for spending budget on to implement it; we have lots of higher priorities.
(*) See the long series of articles on how the Roslyn compiler does so which begins at http://ericlippert.com/2012/12/20/nullable-micro-optimizations-part-one/
While unreachable code is useless and does not affect your execution, code that throws an error is executed. So
if (true) { int hash = constObject.GetHashCode();}
is more or less the same as
throw new NullReferenceException();
You might very well want to throw that null reference. Whereas the unreachable code is just taking up space if it were to be compiled.
It also won't warn about the following code that has the same effect:
throw new NullReferenceException();
There's a balance with warnings. Most compiler errors happen when the compiler can't produce anything meaningful from it.
Some happen with things that affect verifiability, or which cross a threshold of how likely they are to be a bug. For example, the following code:
private void DoNothing(out string str)
{
return;
}
private void UseNothing()
{
string s;
DoNothing(s);
}
Won't compile, though if it did it would do no harm (the only place DoNothing is called doesn't use the string passed, so the fact that it is never assigned isn't a problem). There's just too high a risk that I'm doing something stupid here to let it go.
Warnings are for things that are almost certainly foolish or at least not what you wanted to happen. Dead code is likely enough to be a bug to make a warning worthwhile, but likely enough to be sensible (e.g. trueOrFalse may change as the application is developed) to make an error inappropriate.
Warnings are meant to be useful, rather than nuisances, so the bar for them is put quite high. There's no exact science, but it was deemed that unreachable code made the cut, and trying to deduce when throwing exceptions wasn't the desired behaviour didn't.
It no doubt helps that the compiler already detects unreachable code (and doesn't compile it) but sees one deliberate throw much like another, no matter how convoluted on the one hand or direct on the other.
Why would you even want that to be a compile-time error? Why would you want code that is guaranteed to throw an exception to be invalid at compile time? What if I, the programmer, want the semantics of my program to be:
static void Main(string[] args) {
throw new NullReferenceException();
}
It's my program. The compiler has no business telling me this isn't valid C# code.
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
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.