Visual studio detecting unused return - c#

I've just spent the best part of an hour trying to work out why some code appered to not be working. I was getting no compilation errors of any sort, and have tracked the bug down to calling a function and doing nothing with the return value. The code was a little more involved than the sample below as Class1 is immutable, but it still demonstrates the issue:
public class Class1
{
private int MyVal = 0;
public int GetMyVal()
{
return MyVal;
}
}
public void Tester(){
Class1 Instance = new Class1();
Instance.GetMyVal();
}
The function call to GetMyVal() is as technically useless as it is technically correct. As I say the code was more involved, but this is the core issue.
I'm slightly surprised that VS 2013 (For Web) fails to highlight the issue as clearly nothing is gained from calling GetMyVal. Is there some switches I'm missing to detect this sort of thing or is this beyond the scope of what Visual Studio can accomplish?

I doubt there is/are (m)any editors out there can can give you what you want.
VS will tell you if you have a variable you're not referencing (at least for Pro and Ultimate. Haven't used Web for 2012/2013). However within the scope of Class1, private int MyVal is being referenced within your GetMyVal function so it will not be marked as an unreferenced property.
It can often catch useless pieces of code but I don't see how you expect it to say that your previously initialized and referenced variable is not meaningful. It has no way of knowing that the property in Class1 isn't something you want to use/modify later.
Do correct me if I am misunderstanding your question
Side note: If you can figure out a way to make it do what you're after,might I suggest writing a plugin? Bear in mind that existing plugins like Resharper and FXCop add a world of functionality

Related

What's the explanation of this behavior in C#

Consider this simple console application:
class Program
{
static void Main(string[] args)
{
var human = CreateHuman(args[0]);
Console.WriteLine("Created Human");
Console.ReadLine();
}
public static object CreateHuman(string association)
{
object human = null;
if (association == "is-a")
{
human = new IsAHuman();
}
else
{
human = new HasAHuman();
}
return human;
}
}
public class IsAHuman : Human
{
}
public class HasAHuman
{
public Human Human { get; set; }
}
The Human class is in another assembly, say HumanAssembly.dll. If HumanAssembly.dll exists in the bin directory of our console app, everything would be fine. And as we might expect, by removing it we encounter FileNotFoundException.
I don't understand this part though. Comment human = new IsAHuman(); line, recompile and remove HumanAssembly.dll. Console app won't throw any exception in this case.
My guess is that CLR compiler differentiates between is a and has a associations. In other words, CLR tries to find out and understand and probably load all the types existing in the class definition statement, but it can instantiate a class without knowing what's inside it. But I'm not sure about my interpretation.
I fail to find a good explanation. What is the explanation for this behavior?
You are seeing the behavior of the JIT compiler. Just In Time. A method doesn't get compiled until the last possible moment, just before it is called. Since you removed the need to actually construct a Human object, there is no code path left that forces the jitter to load the assembly. So your program won't crash.
The last remaining reference to Human is the HashAHuman.Human property. You don't use it.
Predicting when the jitter is going to need to load an assembly is not that straight-forward in practice. It gets pretty difficult to reason through when you run the Release build of your code. That normally enables the optimizer that's built into the jitter, one of its core optimization strategies is to inline a method. To do that, it needs access to the method before it is called. You'd need an extra level of indirection, an extra method that has the [MethodImpl(MethodImplOptions.NoInlining)] attribute to stop it from having a peek. That gets to be a bit off into the deep end, always consider a plug-in architecture first, something like MEF.
Here is great explanation of what you are looking for.
The CLR Loader
Specially in the following lines -
This policy of loading types (and assemblies and modules) on demand means that parts of a program that are not used are never brought into
memory. It also means that a running application will often see new
assemblies and modules loaded over time as the types contained in
those files are needed during execution. If this is not the behavior
you want, you have two options. One is to simply declare hidden static
fields of the types you want to guarantee are loaded when your type is
loaded. The other is to interact with the loader explicitly.
As the Bold line says, if you code does not execute a specific line then the types won't be loaded, even if the code is not commented out.
Here is also a similar answer that you might also be interested in -
How are DLLs loaded by the CLR?

MonoTouch mysteriously not aot-compiling methods and properties?

I have a strange problem where MonoTouch seems to be either not compiling methods or not able to find a compiled method it is instructed to call, and only on the device in the Release configuration - Debug builds are fine. I've tried reproducing it with a simpler code sample with no luck, so I doubt you will be able to see the behavior with the code below. But this is essentially what I'm doing:
using System;
using MonoTouch.UIKit;
public class MyClass
{
private UINavigationController _navController;
private UIViewControler _viewController;
public UINavigationController NavController
{
get
{
if (_navController == null)
{
if (_viewController == null)
{
_viewController = new UIViewController();
}
_navController = new UINavigationController(_viewController);
}
return _navController;
}
}
}
Then, in some other method...
public void SomeMethod()
{
MyClass myClass = new MyClass();
var navController = myClass.NavController; // <-- This is where it throws
}
The exception I get is the standard JIT compile message, saying that it attempted to JIT get_NavController(). I find this very strange, because there's no virtual generics, no LINQ, the linker is off, and nothing else that normally causes JITs seems to be involved. I've also verified that it will throw for other methods and properties defined on MyClass, but not the constructor or System.Object inherited methods. Reflection reveals that myClass.GetType().GetMembers() has a MemberInfo for everything I would expect. Yet, only for Release|iPhone, I can't access these methods or properties. The only logical conclusion I can come to is that the aot compilation step is missing them, and I don't know why that would happen at all, let alone only in the Release configuration.
My question is, what could be causing such a situation, and what is the next step to fixing it? I'm not even sure where to go from here on debugging this, or what to file a bug about, because I can't reproduce it out of the context of our (much) larger project.
Update: The exact exception text was requested.
System.ExecutionException: Attempting to JIT compile method
'MyNamespace.MyClass.get_NavController ()' while running with --aot-only
This doesn't look like something that can be solved here.
I suggest filing a bug, and attach the entire project if you're unable to make a smaller test case. You can file private bugs only Xamarin employees have access to if you don't want your project to be publicly visible.
Could you try to explicitly declare the variable
UINavigationController navController = myClass.NavController;
Alternatively, I wonder if this is at all associated with needing to wait for the UIViewController.ViewDidLoad method to be called as the internals of the class may not yet have been initialized?
Just shots in the dark here, I can't think of a reason why your code wouldn't work.

Is it possible to return the code of a method (as a string) using delegates in C#?

I'll exemplify, since I'm not sure if I'm asking the question correctly (English is not my primary language, plus I'm still learning C#).
I've started going through Project Euler, and decided to create an application to keep track of my results, and to put my little C# knowledge to test.
In a particular class I hold static functions that are used to solve each of the problems.
static class Answers()
{
public static string A1(){...}
public static string A2(){...}
public static string A3(){...}
//it goes on
}
Problem objects will be created like this (Problem class definition and object creation in runtime).
class Problem
{
public string Description;
public Solution SolutionFinder;
public Problem(string Desc, Solution Solver)
{
this.Description = Desc;
this.SolutionFinder = Solver;
}
public delegate string Solution();
public string SolveProblem()
{
return SolutionFinder.Invoke();
}
}
This is on my Form creation code:
{
...
List<Problem> Euler = new List<Problem>();
Euler.Add(new Problem("Find the sum of all the multiples of 3 or 5 below 1000.", Answers.A1));
Euler.Add(new Problem("By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.", Answers.A2));
Euler.Add(new Problem("What is the largest prime factor of the number 600851475143 ?", Answers.A3));
...
}
I got the classes and even the delegate thing to work correctly, and I'm thrilled with that. Then I finally decided to show the whole thing on a form. What I'm trying to show is: the description of the problem (this is done) and the code for each method (whatever is inside A1, A2, etc.) whenever I solve a problem using my form.
Is that clear? It's just that I want my form to show the result and how I got the solution for each problem, but without having to retype the contents of each method just for display - the methods are already there.
And please don't mind the messy code and overuse of public members: I understand it's a bad practice, but for now I'm just trying to get through this personal project, and I believe it's OK to do this here since it's just a small learning experience.
Thanks.
[EDIT]
The format I'm looking for is:
void UpdateForm(int Current)
{
Problem CurrentProblem = Euler[Current-1];
string Desc = CurrentProblem.Description;
string Code = CurrentProblem.SolutionFinder.Method.ReturnType.Name;
//I got this far, but I need to display more than just the name of the method!
...
}
To Clarify
Given the method:
public static string A1() {
var answer = 1 + 1;
return answer.ToString();
}
Is it possible to obtain the following lines in a string..?
var answer = 1 + 1;
return answer.ToString();
While it's not the fanciest approach, if you set the "Copy to Output Directory" value to "Copy Always" (or "Copy if newer") via the Properties of the source file (right-click/ Properties), you can parse the code file on your own while optimizing for your coding style.
To add, are you aware that you are basically rebuilding NUnit, aside from the source code dump?
Since at runtime the code is in IL (intermediate language), you actually don't have the readable code at your disposal.
Anyway you could use reflection to create an on-fly decompiler, or use third party library like this one or this one to decompile the methods... but I don't know if they expose some API, I just know them as GUI tools.
You might think about storing your solutiuons (source code) in text files.. (eg. Problem1.projecteuler, ProblemN.projecteuler) and loading these text files both for display and for compilation/execution plugin-style. Check out System.Reflection namespace and do some web searches for "C# plugin tutorial" or some such to get started.
valeriano your static methods could be Linq Expressions, then you could iterate through each node of the expression. Using Reflection works too but you need more code
There's no easy way to run code (ie: contents of a method) from a string since C# is already compiled before its executable is launched.
However, there are tricks you can do with Reflection and Diagnostics, but that requires you to run your code in Debug mode. If it's just a small app, this shouldn't be a problem. But larger applications with suffer performance issues when ran in debug mode.
For more info: Execute a string in C# 4.0

C# Extension Method Oddity during Unit Test

Using Visual Studio 2008 / C# / VS Unit Testing.
I have a very straightforward extension method, that will tell me if an object is of a specific type:
public static bool IsTypeOf<T, O>(this T item, O other)
{
if (!(item.GetType() is O))
return false;
else
return true;
}
It would be called like:
Hashtable myHash = new Hashtable();
bool out = myHash.IsTypeOf(typeof(Hashtable));
The method works just fine when I run the code in debug mode or if I debug my unit tests. However, the minute I just run all the unit tests in context, I mysteriously get a MissingMethodException for this method. Strangely, another extension method in the same class has no problems.
I am leaning towards the problem being something other than the extension method itself. I have tried deleting temporary files, closing/reopening/clean/rebuilding the solution, etc. So far nothing has worked.
Has anyone encountered this anywhere?
Edit: This is a simplified example of the code. Basically, it is the smallest reproducible example that I was able to create without the baggage of the surrounding code. This individual method also throws the MissingMethodException in isolation when put into a unit test, like above. The code in question does not complete the task at hand, like Jon has mentioned, it is more the source of the exception that I am currently concerned with.
Solution: I tried many different things, agreeing with Marc's line of thinking about it being a reference issue. Removing the references, cleaning/rebuilding, restarting Visual Studio did not work. Ultimately, I ended up searching my hard drive for the compiled DLL and removed it from everywhere that did not make sense. Once removing all instances, except the ones in the TestResults folder, I was able to rebuild and rerun the unit tests successfully.
As to the content of the method, it was in unit testing that I discovered the issue and was never able to get the concept working. Since O is a RunTimeType, I do not seem to have much access to it, and had tried to use IsAssignableFrom() to get the function returning correctly. At this time, this function has been removed from my validation methods to be revisited at another time. However, prior to removing this, I was still getting the original issue that started this post with numerous other methods.
Post-solution: The actual method was not as complex as I was making it out to be. Here is the actual working method:
public static void IsTypeOf<T>(this T item, Type type)
{
if (!(type.IsAssignableFrom(item.GetType())))
throw new ArgumentException("Invalid object type");
}
and the unit test to verify it:
[TestMethod]
public void IsTypeOfTest()
{
Hashtable myTable = new Hashtable();
myTable.IsTypeOf(typeof(Hashtable));
try
{
myTable.IsTypeOf(typeof(System.String));
Assert.Fail("Type comparison should fail.");
}
catch (ArgumentException)
{ }
}
Usually, a MissingMethodException means that you are loading a different version of the dll to the one you referenced during build, and the actual dll you are loading (at run-time) doesn't have the method the compiler found (at compile-time).
Check that you haven't somehow got various versions of the dll referenced by different projects. It could be that when you run it in debug mode, some other code makes the correct dll load first, but when running in-context, this other code doesn't run - so the incorrect version loads instead.
This would apply doubly if the failing method was added recently, so might not be in the older version referenced.
If you are using full assembly versioning, you might be able to watch the debug output to see exactly which assembly loads.
I am speculating here.
Put a constraint on the method to see if that helps
Pseudocode
public static bool IsTypeOf(this T item, O other) Where T: object, O: Type
{
}
Also, which class is this method in?
EDIT: Is this class, part of the assembly which is being tested?

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