C# array automatically gets set to null, why does this happen? [duplicate] - c#

While debugging I tried to save intermediate results of a calculation to a variable so that when a breakpoint condition is met I could check that value. However C# compiler (or CLR) optimized away that variable as unused. I solved the problem by making the variable a public field of the class, however I'd like to know if there is a straightforward solution to this problem.
"Optimize code" checkbox is unchecked. The build configuration is Debug.
Edit: Found that it only affects some unused variables in iterators that would normally end up as fields in the automatically generated iterator class; unused variables that are scoped within blocks not containing yield statements are retained.

The lazy option would be.... use the value, ideally in a way that doesn't allow it to be held on the stack. For example:
var tmp = SomeMethod();
// your other code
Debug.WriteLine(tmp);
the use of the value as an argument means it must be retained, but that line is automatically not compiled into release builds.
However! I must emphasize that locals are pretty-much always retained in an unoptimized/debug build, so I'm finding the scenario from the question hard to envisage.

If you are using Visual Studio, why not just add a breakpoint on the line following the line on which the calculation is being made, and then you can simply hover over the calculation to see the result in the intellisense/tooltip popup? I also think that you can add the calculation to the "watch" screen and view the result that way as well.
This is usually how I view the results of things I am debugging. Alternatively, you could just use the temp variable you created in some simple way to avoid getting the warning.
For example:
Console.Write(tempVariable);

Handy utility:
using static _globals;
static class _globals
{
[MethodImpl(MethodImplOptions.NoInlining), DebuggerHidden]
public static void Nop<T>(out T x) => x = default(T);
};
class Program
{
static void Main()
{
int i; // unreferenced variable
/// ...
Nop(out i);
/// ...
}
};

You need uncheck options "Optimize code" in project options for Debug build.

In my case "Optimize code" option was unchecked, still I was facing this issue. I checked it, build project then unchecked it and buid project again. This fixed issue for me.

Related

Delegate allocation: capture of 'this' reference in JetBrains Rider

When I was doing my code in C# I found a yellow line below arrow function as shown in image, I hovered my cursor over it and it showed
"Delegate allocation: capture of 'this' reference"
I searched this on google but didn't find anything.
I also found that when I remove initRemoteConfig field than that line goes away.
So can anybody explain what's happening here and what to do to remove this warning?
This is about lambda capturing outer context (docs about capturing a local variable, or there are some answers about this on SO). It seems that initRemoteConfig is a field/property on class containing this code, so your lambda needs to capture current instance of this class.
Also this is not a build in rider inspection it comes from heap allocations viewer which helps you to prevent unnecessary allocations, but sometimes you still need to allocate, so you can't always fix this warnings (i.e. this plugin will always "warn" about any allocation and it is up to you to decide if it is necessary or not). In this particular case, if it is suitable for your context, you can make the initRemoteConfig property/field a static one, i.e. something like this:
private static int initRemoteConfig;
Action x = () =>
{
initRemoteConfig = 3;
};
will not give you this warning (but has some other drawbacks).

Bug tracking by debugging when a variable changes

I'm a beginner at programming and having a very difficult time tracking down bugs, this happens because usually place a variable on watch, and keep pressing f5 until i notice some change. I'm on visual c# 2010 and i have 18000 lines of code, so only with some luck i do get to catch the problem.
Is there a way to instantly go to the line of code when a variable changes?
You can change your variable into a property and put a breakpoint on the setter. Then you can have a single breakpoint that will hit each time a piece of code changes its value.
So if you have:
int myVariable;
Change it to:
int myVariable {
get;
set; // <-- Put your breakpoint here
}
This sounds like a design problem. Ideally, you should limit the places where a variable changes to very specific locations in your code. This is one reason to avoid global variables and static variables unless you have very good reasons to use them. Even then, you should define accessor methods as an interface for these variables rather than changing them directly.
As you debug your code, I suggest you look for ways you can improve it so that debugging isn't so difficult in the future.
You can have conditional breakpoints, that will only be hit when a condition is met.
So, assuming you have an index variable indx, you can put a conditinal break point, saying only stop when value = 7, and then it'll stop there when you're condition changes...
Have a look at this msdn page
and at this youtube tutorial.
In native code, your best bet would be to setup a data breakpoint. A data breakpoint fires when the data changes, irrespective of where the change comes from.
You can't do this for .NET however. You can't ask the debugger to break when the value of a variable changes. But, not all hope is lost. Do a "Find Usages" or "Find References" on the variable in question to find all places in your code that make use of the variable. Then set a breakpoint at each of those locations to see when the value of the variable changes.

String assignment mystic issue. Variable name affects behavior

I have the following code inside a method:
string username = (string)context["UserName"];
string un = (string)context["UserName"];
The problem is that the first string "username" is not assigned, while the second does.
To make it more strange, when I have stopped the debugging after the first line and copied the line to the Immediate window, dropping the varible type delaration, it was assigned succesfully.
I have made rebuild all and checked project properties which seems to be OK.
The context variable is a System.Configuration.SettingsContext, which is a hash table. To be more specific, I'm implementing a profile provider, the GetPropertyValues method.
I am using VS 2012 and .NET 4.5
EDIT:
I am using code contract in my project, which uses compile time code injection for runtime checking. I disabled it and all is working well. I'll try to remove contracts one by one to find which one is causing the problem.
What you are seeing is similar to a Code Contracts bug I saw before. I wrote something about it here a few months back. If you have this bug, you probably also have a lambda or LINQ expression in your method that uses username.
For future reference, this is the bug I saw:
I had in the same method a lambda expression capturing a local variable, lets say values, and a Contract.Requires() expression checking something completely unrelated. While debugging that method, the debugger shows in Locals the variable values twice, and reports the value of values always as null even when this is clearly not the case.
To reproduce:
static void Reproduction(string argument)
{
Contract.Requires(argument != null); // <-- (1)
int[] values = new int[1];
Debug.Assert(values != null);
Func<int, bool> d = i => values[i] >= 0; // <-- (2)
Console.WriteLine(values);
}
Put a breakpoint somewhere in this method after the assignment to values and ensure that the method gets called. When the debugger hits the breakpoint, look at the Locals list of Visual Studio for the duplicate variable. Hover the mouse over values to find that it gets reported as being null, something which is clearly not the case.
The problem disappears when removing either the contract (1) or the line with the lambda (2).
After investigating and desabling contracts I found that the problem appears only when runtime contracts checking is enabled and this contract appears:
Contract.Ensures(Contract.Result<System.Configuration.SettingsPropertyValueCollection>() != null);
If I delete this line, the code works, so it looks like code contracts bug, though I couldn't recreate it on a test project.

Getting a Method's Return Value in the VS Debugger

Is it possible to get a method's return value in the Visual Studio debugger, even if that value isn't assigned to a local variable? For example, I'm debugging the following code:
public string Foo(int valueIn)
{
if (valueIn > 100)
return Proxy.Bar(valueIn);
else
return "Not enough";
}
Since I'm not setting any local variables in Foo, and assuming I'm not setting a break point in whatever's calling Foo, is there a way to see what the return value is if I have a breakpoint inside of Foo (or another way)? I don't have much experience with the Autos or Intermediate windows, so I'm not sure if those are even a valid option or not.
You can set a breakpoint in Foo, open the immediate window and run the following command:
? Foo(valueIn)
This will print the return value in the Immediate Window.
You can also copy the expression and paste it into the Watch window, though I would do this only if I am certain that the call has no side effects (otherwise you can get confusing results).
You can always switch to disassembler view and step through the individual instructions. The return value will be in #eax (or #rax) just before you execute the 'ret' instruction.
The answer to a similar question out there:
Since Visual Studio 2013, you can add the variable $ReturnValue to the watch list. It contains the actual return value from a function.
Credits to Jesper Jensen.
No, I don't know of a way to do this. I would put a breakpoint in the caller and look at the return value there.
You can also highlight any expression in the debugger and right-click -> quick watch. That will execute the expression (assuming it's valid) and give you the value.
Visual Studio 2013 now has the ability in the Autos window to display the last value returned by a function, alleviating the need to re-execute it in the Output window or introduce a temporary variable:
http://blogs.msdn.com/b/visualstudioalm/archive/2013/06/27/seeing-function-return-values-in-the-debugger-in-visual-studio-2013.aspx
You can always use your watch box to evaluate function calls.
Foo(valueIn);
This will only work if your Proxy.Bar(valueIn) is time independent though.
A workaround is to use a Pascal-style result variable:
public string Foo(int valueIn)
{
string result;
if (valueIn > 100)
result = Proxy.Bar(valueIn);
else
result = "Not enough";
return result;
}
This is good style in my opinion for longer functions. For very short ones like the one above it could be considered overkill, but it does get around the debugger problem.

break whenever a file (or class) is entered

In Visual Studio, is there any way to make the debugger break whenever a certain file (or class) is entered? Please don't answer "just set a breakpoint at the beginning of every method" :)
I am using C#.
Macros can be your friend. Here is a macro that will add a breakpoint to every method in the current class (put the cursor somewhere in the class before running it).
Public Module ClassBreak
Public Sub BreakOnAnyMember()
Dim debugger As EnvDTE.Debugger = DTE.Debugger
Dim sel As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
Dim editPoint As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint()
Dim classElem As EnvDTE.CodeElement = editPoint.CodeElement(vsCMElement.vsCMElementClass)
If Not classElem Is Nothing Then
For Each member As EnvDTE.CodeElement In classElem.Children
If member.Kind = vsCMElement.vsCMElementFunction Then
debugger.Breakpoints.Add(member.FullName)
End If
Next
End If
End Sub
End Module
Edit: Updated to add breakpoint by function name, rather than file/line number. It 'feels' better and will be easier to recognise in the breakpoints window.
You could start by introducing some sort of Aspect-Oriented Programming - see for instance
this explanation - and then put a breakpoint in the single OnEnter method.
Depending on which AOP framework you choose, it'd require a little decoration in your code and introduce a little overhead (that you can remove later) but at least you won't need to set breakpoints everywhere. In some frameworks you might even be able to introduce it with no code change at all, just an XML file on the side?
Maybe you could use an AOP framework such as PostSharp to break into the debugger whenever a method is entered. Have a look at the very short tutorial on this page for an example, how you can log/trace whenever a method is entered.
Instead of logging, in your case you could put the Debugger.Break() statement into the OnEntry-handler. Although, the debugger would not stop in your methods, but in the OnEntry-handler (so I'm not sure if this really helps).
Here's a very basic sample:
The aspect class defines an OnEntry handler, which calls Debugger.Break():
[Serializable]
public sealed class DebugBreakAttribute : PostSharp.Laos.OnMethodBoundaryAspect
{
public DebugBreakAttribute() {}
public DebugBreakAttribute(string category) {}
public string Category { get { return "DebugBreak"; } }
public override void OnEntry(PostSharp.Laos.MethodExecutionEventArgs eventArgs)
{
base.OnEntry(eventArgs);
// debugger will break here. Press F10 to continue to the "real" method
System.Diagnostics.Debugger.Break();
}
}
I can then apply this aspect to my class, where I want the debugger to break whenever a method is called:
[DebugBreak("DebugBreak")]
public class MyClass
{
public MyClass()
{
// ...
}
public void Test()
{
// ...
}
}
Now if I build and run the application, the debugger will stop in the OnEntry() handler whenever one of the methods of MyClass is called. All I have to do then, is to press F10, and I'm in the method of MyClass.
Well, as everyone is saying, it involves setting a breakpoint at the beginning of every method. But you're not seeing the bigger picture.
For this to work at all, a breakpoint has to be set at the beginning of every method. Whether you do it manually, or the debugger does it automatically, those breakpoints must be set for this to work.
So, the question really becomes, "If there enough of a need for this functionality, that it is worth building into the debugger an automatic means of setting all those breakpoints?". And the answer is, "Not Really".
This feature is implemented in VS for native C++. crtl-B and specify the 'function' as "Classname::*", this sets a breakpoint at the beginning of every method on the class. The breakpoints set are grouped together in the breakpoints window (ctrl-alt-B) so they can be enabled, disabled, and removed as a group.
Sadly the macro is likely the best bet for managed code.
This works fine in WinDbg:
bm exename!CSomeClass::*
(Just to clarify, the above line sets a breakpoint on all functions in the class, just like the OP is asking for, without resorting to CRT hacking or macro silliness)
You could write a Visual Studio macro that obtained a list of all of the class methods (say, by reading the .map file produced alongside the executable and searching it for the proper symbol names (and then demangling those names)), and then used Breakpoints.add() to programmatically add breakpoints to those functions.
System.Diagnostics.Debugger.Break();
(at the beginning of every method)
No. Or rather, yes, but it involves setting a breakpoint at the beginning of every method.
Use Debugger.Break(); (from the System.Diagnostics namespace)
Put it at the top of each function you wish to have "broken"
void MyFunction()
{
Debugger.Break();
Console.WriteLine("More stuff...");
}
Isn't the simplest method to get closest to this to simply set a break point in the constructor (assuming you have only one - or each of them in the case of multiple constructors) ?
This will break into debugging when the class is first instantiated in the case of a non-static constructor, and in the case of a static constructor/class, you'll break into debugging as soon as Visual Studio decides to initialize your class.
This certainly prevents you from having to set a breakpoint in every method within the class.
Of course, you won't continue to break into debugging on subsequent re-entry to the class's code (assuming you're using the same instantiated object the next time around), however, if you re-instantiate a new object each time from within the calling code, you could simulate this.
However, in conventional terms, there's no simple way to set a single break point in one place (for example) and have it break into debugging every time a class's code (from whichever method) is entered (as far as I know).
Assuming that you're only interested in public methods i.e. when the class methods are called "from outside", I will plug Design by Contract once more.
You can get into the habit of writing your public functions like this:
public int Whatever(int blah, bool duh)
{
// INVARIANT (i)
// PRECONDITION CHECK (ii)
// BODY (iii)
// POSTCONDITION CHECK (iv)
// INVARIANT (v)
}
Then you can use the Invariant() function that you will call in (i) and set a breakpoint in it. Then inspect the call stack to know where you're coming from. Of course you will call it in (v), too; if you're really interested in only entry points, you could use a helper function to call Invariant from (i) and another one from (v).
Of course this is extra code but
It's useful code anyway, and the structure is boilerplate if you use Design by Contract.
Sometimes you want breakpoints to investigate some incorrect behaviour eg invalid object state, in that case invariants might be priceless.
For an object which is always valid, the Invariant() function just has a body that returns true. You can still put a breakpoint there.
It's just an idea, it admittedly has a footstep, so just consider it and use it if you like it.
Joel, the answer seems to be "no". There isn't a way without a breakpoint at every method.
To remove the breakpoints set by the accepted answer add another macro with the following code
Public Sub RemoveBreakOnAnyMember()
Dim debugger As EnvDTE.Debugger = DTE.Debugger
Dim bps As Breakpoints
bps = debugger.Breakpoints
If (bps.Count > 0) Then
Dim bp As Breakpoint
For Each bp In bps
Dim split As String() = bp.File.Split(New [Char]() {"\"c})
If (split.Length > 0) Then
Dim strName = split(split.Length - 1)
If (strName.Equals(DTE.ActiveDocument.Name)) Then
bp.Delete()
End If
End If
Next
End If
End Sub
Not that I'm aware of. The best you can do is to put a breakpoint in every method in the file or class. What are you trying to do? Are you trying to figure out what method is causing something to change? If so, perhaps a data breakpoint will be more appropriate.
You could write a wrapper method through which you make EVERY call in your app. Then you set a breakpoint in that single method. But... you'd be crazy to do such a thing.
You could put a memory break point on this, and set it to on read. I think there should be a read most of the time you call a member function. I'm not sure about static functions.
you can use the following macro:
#ifdef _DEBUG
#define DEBUG_METHOD(x) x DebugBreak();
#else
#define DEBUG_METHOD(x) x
#endif
#include <windows.h>
DEBUG_METHOD(int func(int arg) {)
return 0;
}
on function enter it will break into the debugger
IF this is C++ you are talking about, then you could probably get away with, (a hell of a lot of work) setting a break point in the preamble code in the CRT, or writing code that modifies the preamble code to stick INT 3's in there only for functions generated from the class in question... This, BTW, CAN be done at runtime... You'd have to have the PE file that's generated modify itself, possibly before relocation, to stick all the break's in there...
My only other suggestion would be to write a Macro that uses the predefined macro __FUNCTION__, in which you look for any function that's part of the class in question, and if necessary, stick a
__asm { int 3 }
in your macro to make VS break... This will prevent you from having to set break points at the start of every function, but you'd still have to stick a macro call, which is a lot better, if you ask me. I think I read somewhere on how you can define, or redefine the preamble code that's called per function.. I'll see what I can find.
I would think I similar hack could be used to detect which FILE you enter, but you STILL have to place YOUR function macro's all over your code, or it will never get called, and, well, that's pretty much what you didn't want to do.
If you are willing to use a macro then the accepted answer from this question
Should be trivially convertible to you needs by making the search function searching for methods, properties and constructors (as desired), there is also quite possibly a way to get the same information from the the ide/symbols which will be more stable (though perhaps a little more complex).
You can use Debugger.Launch() and Debugger.Break() in the assembly System.Diagnostics
Files have no existence at runtime (consider that partial classes are no different -- in terms of code -- from putting everything in a single file). Therefore a macro approach (or code in every method) is required.
To do the same with a type (which does exist at runtime) may be able to be done, but likely to be highly intrusive, creating more potential for heisenbugs. The "easiest" route to this is likely to be making use of .NET remoting's proxy infrastructure (see MOQ's implementation for an example of using transparent proxy).
Summary: use a macro, or select all followed by set breakpoint (ctrl-A, F9).
Mad method using reflection. See the documentation for MethodRental.SwapMethodBody for details. In pseudocode:
void SetBreakpointsForAllMethodsAndConstructorsInClass (string classname)
{
find type information for class classname
for each constructor and method
get MSIL bytes
prepend call to System.Diagnostics.Debugger.Break to MSIL bytes
fix up MSIL code (I'm not familiar with the MSIL spec. Generally, absolute jump targets need fixing up)
call SwapMethodBody with new MSIL
}
You can then pass in classname as a runtime argument (via the command line if you want) to set breakpoints on all methods and constructors of the given class.

Categories